In this tutorial, we are going to learn how to capitalize the first letter of a column in the Pandas dataframe. We are going to use the capitalize method of str. Let's create a dataframe and use the capitalize method of str to complete the task. We are creating the DataFrame from the lists of Python.
Example
# importing pandas library
import pandas as pd
# lists for the DataFrame columns
names = ['tutorialspoint', 'mohit', 'sharma']
age = [25, 34, 21]
# creating a Dataframe
data_frame = pd.DataFrame({'Name': names, 'Age': age})
# checking the data_frame
print(data_frame)Output
If you run the above program, you will get the following results.
Name Age 0 tutorialspoint 25 1 mohit 34 2 sharma 21
Let's capitalize on the Name column of the data_frame.
- Take the column using index name and capitalize it.
- Reassign the same to the column.
Example
Let's see the code for the same.
# importing pandas library
import pandas as pd
# lists for the DataFrame columns
names = ['tutorialspoint', 'mohit', 'sharma']
age = [25, 34, 21]
# creating a Dataframe
data_frame = pd.DataFrame({'Name': names, 'Age': age})
# capitalizing the column Name and assigning the same
data_frame['Name'] = data_frame['Name'].str.capitalize()
# printing the data_framer
print(data_frame)Output
If you run the above code, you will get the following results.
Name Age 0 Tutorialspoint 25 1 Mohit 34 2 Sharma 21
We can achieve the same using functions as well. But, using the capitalize method of str is more convenient and easy.
Conclusion
If you have any doubts regarding the tutorial, mention them in the comment section.