When working with data in a Pandas dataframe, you may come across a situation where you need to apply uppercase to a specific column. This can be useful for standardizing data or when you need the column values to be in uppercase for further analysis or comparison. In this article, we will explore different methods to achieve this in Python using Pandas.
Method 1: Using the str.upper() Method
One straightforward way to apply uppercase to a column in a Pandas dataframe is by using the str.upper()
method. This method converts all the string values in the specified column to uppercase.
import pandas as pd Create a sample dataframe data = {'Name': ['John', 'Alice', 'Bob'], 'Age': [25, 30, 35], 'City': ['New York', 'London', 'Paris']} df = pd.DataFrame(data) Apply uppercase to the 'Name' column df['Name'] = df['Name'].str.upper() print(df)
Output:
Name Age City 0 JOHN 25 New York 1 ALICE 30 London 2 BOB 35 Paris
As you can see, the values in the ‘Name’ column have been converted to uppercase using the str.upper()
method.
Method 2: Using the apply() Function
Another way to apply uppercase to a column is by using the apply()
function along with a lambda function. This allows us to apply a custom transformation to each value in the column.
Using apply() and lambda function to apply uppercase df['Name'] = df['Name'].apply(lambda x: x.upper()) print(df)
Output:
Name Age City 0 JOHN 25 New York 1 ALICE 30 London 2 BOB 35 Paris
In this method, we create a lambda function that takes each value in the ‘Name’ column and applies the upper()
method to convert it to uppercase. The apply()
function then applies this lambda function to each value in the column.
Method 3: Using the map() function with the str.upper() method
df['Name'] = df['Name'].map(str.upper)
Output:
Name Age City 0 JOHN 25 New York 1 ALICE 30 London 2 BOB 35 Paris
Last Updated on May 17, 2023 by admin