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
Selected Reading
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.
Using str.upper() Method
We can convert a column to uppercase using the str.upper() method. This is the most common and efficient approach for string operations in pandas.
# 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)
---------------------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
Using apply() Method
We can also achieve the same result using the apply() method with a lambda function. This approach is more flexible for custom transformations.
# 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)
---------------------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
Comparison
| Method | Performance | Best For |
|---|---|---|
str.upper() |
Faster | Simple string transformations |
apply() |
Slower | Complex custom functions |
Conclusion
Use str.upper() for simple uppercase conversion as it's more efficient. The apply() method is better suited for complex transformations that require custom logic.
Advertisements
