Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Capitalize first letter of a column in Pandas dataframe
A Pandas DataFrame is similar to a table with rows and columns. Sometimes we need to capitalize the first letter of strings in a specific column, which can be achieved using the str.capitalize() method.
Creating a DataFrame
Let's start by creating a DataFrame with columns for days and subjects ?
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'Day': ['mon', 'tue', 'wed', 'thu', 'fri'],
'Subject': ['math', 'english', 'science', 'music', 'games']
})
print(df)
Day Subject
0 mon math
1 tue english
2 wed science
3 thu music
4 fri games
Using str.capitalize() Method
The str.capitalize() method capitalizes the first letter of each string and converts the rest to lowercase. We can apply it to any column in the DataFrame ?
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'Day': ['mon', 'tue', 'wed', 'thu', 'fri'],
'Subject': ['math', 'english', 'science', 'music', 'games']
})
# Capitalize the first letter of the Day column
df['Day'] = df['Day'].str.capitalize()
print(df)
Day Subject
0 Mon math
1 Tue english
2 Wed science
3 Thu music
4 Fri games
Capitalizing Multiple Columns
You can also capitalize multiple columns at once by applying the method to each column ?
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'Day': ['mon', 'tue', 'wed', 'thu', 'fri'],
'Subject': ['math', 'english', 'science', 'music', 'games']
})
# Capitalize both columns
df['Day'] = df['Day'].str.capitalize()
df['Subject'] = df['Subject'].str.capitalize()
print(df)
Day Subject
0 Mon Math
1 Tue English
2 Wed Science
3 Thu Music
4 Fri Games
Using title() Method
For proper title case formatting, you can also use str.title() which capitalizes the first letter of each word ?
import pandas as pd
# DataFrame with multi-word entries
df = pd.DataFrame({
'Course': ['data science', 'machine learning', 'web development']
})
# Using title() for proper title case
df['Course'] = df['Course'].str.title()
print(df)
Course
0 Data Science
1 Machine Learning
2 Web Development
Conclusion
Use str.capitalize() to capitalize only the first letter of each string in a column. Use str.title() when you need to capitalize the first letter of each word in multi-word strings.
