Open In App

Capitalize first letter of a column in Pandas dataframe

Last Updated : 11 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important.

One might encounter a situation where we need to capitalize any specific column in given dataframe. Let's see how can we capitalize first letter of a column in Pandas dataframe.

Let's create a dataframe from the dict of lists.

Python
# Create a simple dataframe 

# importing pandas as pd 
import pandas as pd 


# creating a dataframe 
df = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 
				'B': ['masters', 'graduate', 'graduate', 
								'Masters', 'Graduate'], 
				'C': [27, 23, 21, 23, 24]}) 

df 

Output:

There are certain methods we can change/modify the case of column in pandas dataframe. Let's see how can we capitalize first letter of columns using capitalize() method.

Method #1:

Python
# Create a simple dataframe 

# importing pandas as pd 
import pandas as pd 


# creating a dataframe 
df = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 
				'B': ['masters', 'graduate', 'graduate', 
								'Masters', 'Graduate'], 
				'C': [27, 23, 21, 23, 24]}) 

df['A'] = df['A'].str.capitalize() 

df 

Output:

Method #2:

Using lambda with capitalize() method

Python
# Create a simple dataframe 

# importing pandas as pd 
import pandas as pd 


# creating a dataframe 
df = pd.DataFrame({'A': ['john', 'bODAY', 'minA', 'Peter', 'nicky'], 
				'B': ['masters', 'graduate', 'graduate', 
								'Masters', 'Graduate'], 
				'C': [27, 23, 21, 23, 24]}) 

df['A'] = df['A'].apply(lambda x: x.capitalize()) 
df['A']

Output:

imp1



Next Article

Similar Reads