Capitalize first letter of a column in Pandas dataframe


A pandas dataframe is similar to a table with rows and columns. Sometimes we may have a need of capitalizing the first letters of one column in the dataframe which can be achieved by the following methods.

Creating a Dataframe

In the below example we first create a dataframe with column names as Day and Subject.

Example

import pandas as pd
# A dataframe
df = pd.DataFrame({'Day': ['mon', 'tue', 'wed', 'thu', 'fri'], 'Subject': ['Math', 'english', 'science', 'music', 'games']})
print(df)

Output

Running the above code gives us the following result −

      Day    Subject
0     mon       Math
1     tue    english
2     wed science
3     thu music
4     fri games

Applying capitalize() function

We apply the str.capitalize() function to the above dataframe for the column named Day. As you can notice, the name of all the days are capitalized at the first letter.

Example

import pandas as pd
# A dataframe
df = pd.DataFrame({'Day': ['mon', 'tue', 'wed', 'thu', 'fri'], 'Subject': ['Math', 'english', 'science', 'music', 'games']})
#print(df)
df['Day'] = df['Day'].str.capitalize()
print(df)

Output

Running the above code gives us the following result −

      Day       Subject
0     Mon          Math
1     Tue       english
2     Wed       science
3     Thu         music
4     Fri         games

Updated on: 07-Aug-2019

892 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements