Apply uppercase to a column in Pandas dataframe in Python


In this tutorial, we are going to see how to make a column of names to uppercase in DataFrame. Let's see different ways to achieve our goal.

Example

We can assign a column to the DataFrame by making it uppercase using the upper() method.

Let's see the code.

# importing the pandas package
import pandas as pd
# data for DataFrame
data = {
   'Name': ['Hafeez', 'Aslan', 'Kareem'],
   'Age': [19, 21, 18],
   'Profession': ['Developer', 'Engineer', 'Artist']
}
# creating DataFrame
data_frame = pd.DataFrame(data)
# displaying the DataFrame
print('---------------------Before-------------------')
print(data_frame)
print()
# making the Name column strings to upper case
data_frame['Name'] = data_frame['Name'].str.upper()
# displaying the DataFrame
print('---------------------After-------------------')
print(data_frame)

Output

If you run the above program, you will get the following results.

---------------------Before-------------------
Name Age Profession
0 Hafeez 19 Developer
1 Aslan 21 Engineer
2 Kareem 18 Artist
---------------------After-------------------
Name Age Profession
0 HAFEEZ 19 Developer
1 ASLAN 21 Engineer
2 KAREEM 18 Artist

Example

We can also achieve the same thing using apply() method of DataFrame. Let's see the related code.

# importing the pandas package
import pandas as pd
# data for DataFrame
data = {
   'Name': ['Hafeez', 'Aslan', 'Kareem'],
   'Age': [19, 21, 18],
   'Profession': ['Developer', 'Engineer', 'Artist']
}
# creating DataFrame
data_frame = pd.DataFrame(data)
# displaying the DataFrame
print('---------------------Before-------------------')
print(data_frame)
print()
# making the Name column strings to upper case
data_frame['Name'] = data_frame['Name'].apply(lambda name : name.upper())
# displaying the DataFrame
print('---------------------After-------------------')
print(data_frame)

Output

If you run the above program, you will get the following results.

---------------------Before-------------------
Name Age Profession
0 Hafeez 19 Developer
1 Aslan 21 Engineer
2 Kareem 18 Artist
---------------------After-------------------
Name Age Profession
0 HAFEEZ 19 Developer
1 ASLAN 21 Engineer
2 KAREEM 18 Artist

Conclusion

I hope you learned something from the tutorial. If you have any doubts regarding the tutorial, ask them in the comment section.

raja
Published on 01-Nov-2019 09:47:01
Advertisements