Capitalize First Letter of a Column in Pandas Dataframe
In this article, we’ll learn how to capitalize the first letter of each value in a Pandas DataFrame column. For example, converting john to John or new york to New york improves readability in your dataset.
Below is a sample DataFrame we’ll use to demonstrate different methods:
import pandas as pd
df = pd.DataFrame({'A': ['john', 'harry', 'alice', 'peter', 'nicky'],
'B': ['masters', 'graduate', 'graduate','Masters', 'Graduate'],
'C': [27, 23, 21, 23, 24]})
print(df)
Output
A B C 0 john masters 27 1 harry graduate 23 2 alice graduate 21 3 peter Masters 23 4 nicky Graduate 24
Let's explore different methods to capitalize first letter of a column in pandas dataframe.
Using .str.title()
If your strings contain multiple words, .str.title() capitalizes the first letter of each word, not just the first word. This method is useful for names, city names, or multi-word phrases.
df['A'] = df['A'].str.title()
print(df)
Output
A B C
0 John masters 27
1 Harry graduate 23
2 Alice graduate 21
3 Peter Masters 23
4 Nicky Graduate 24
Using .str.capitalize()
.str.capitalize() function in Pandas is used to capitalize the first letter of each string in a column while converting the rest of the characters to lowercase.
df['A'] = df['A'].str.capitalize()
print(df)
Output
A B C
0 John masters 27
1 Harry graduate 23
2 Alice graduate 21
3 Peter Masters 23
4 Nicky Graduate 24
Using .apply() with lambda
.apply() function allows applying a custom function to each element of a column. Here, we use lambda with Python’s built-in capitalize() method to achieve the same result.
df['A'] = df['A'].apply(lambda x: x.capitalize())
print(df)
Output
A B C
0 John masters 27
1 Harry graduate 23
2 Alice graduate 21
3 Peter Masters 23
4 Nicky Graduate 24
Using Regular Expressions with .str.replace()
You can use a regex pattern to match the first letter of each string and convert it to uppercase manually.
df['A'] = df['A'].str.replace(r'(^[a-z])', lambda x: x.group(1).upper(), regex=True)
print(df)
Output
A B C
0 John masters 27
1 Harry graduate 23
2 Alice graduate 21
3 Peter Masters 23
4 Nicky Graduate 24