Apply String Methods to Multiple Columns of a Dataframe

Below are the possible approaches to apply string methods to multiple columns of a dataframe in Python:

  • Using applymap
  • Using apply with lambda
  • Using assign with str accessor

Apply String Methods To Multiple Columns Of A Dataframe Using applymap

In this example, we are using the applymap function to apply the str.lower method to all elements in the specified columns (‘name‘ and ‘city‘). This converts all string values in these columns to lowercase.

Python
import pandas as pd

df = pd.DataFrame({
    'name': ['w3wiki', 'CodingForAll', 'CodeWars'],
    'city': ['Noida', 'San Francisco', 'Los Angeles']
})

df[['name', 'city']] = df[['name', 'city']].applymap(lambda x: x.lower())
print(df)

Output
            name           city
0  w3wiki          noida
1   codingforall  san francisco
2       codewars    los angeles

Apply String Methods To Multiple Columns Of A Dataframe Using apply with lambda

In this example, we are using the apply method with a lambda function to apply the str.upper method to each element in the ‘name‘ and ‘city‘ columns. This converts all string values in these columns to uppercase.

Python
import pandas as pd

df = pd.DataFrame({
    'name': ['w3wiki', 'CodingForAll', 'CodeWars'],
    'city': ['Noida', 'San Francisco', 'Los Angeles']
})

df['name'] = df['name'].apply(lambda x: x.upper())
df['city'] = df['city'].apply(lambda x: x.upper())
print(df)

Output
            name           city
0  w3wiki          NOIDA
1   CODINGFORALL  SAN FRANCISCO
2       CODEWARS    LOS ANGELES

Apply String Methods To Multiple Columns Of A Dataframe Using assign with str accessor

In this example, we are using the assign method with the str accessor in pandas to apply the capitalize string method to the ‘name‘ and ‘city‘ columns of the dataframe, converting the first letter of each word to uppercase.

Python
import pandas as pd

df = pd.DataFrame({
    'name': ['w3wiki', 'codingforall', 'codewars'],
    'city': ['noida', 'san francisco', 'los angeles']
})

df = df.assign(name=df['name'].str.capitalize(), city=df['city'].str.capitalize())
print(df)

Output
            name           city
0  w3wiki          Noida
1   Codingforall  San francisco
2       Codewars    Los angeles

Apply String Methods Across Multiple Columns in a Pandas DataFrame

We are given a dataframe in Pandas with multiple columns, and we want to apply string methods to transform the data within these columns. In this article, we will explore three different approaches to applying string methods to multiple columns of a dataframe.

Similar Reads

Apply String Methods to Multiple Columns of a Dataframe

Below are the possible approaches to apply string methods to multiple columns of a dataframe in Python:...