How to convert a column of strings to lowercase in a Pandas DataFrame?

Published on Aug. 22, 2023, 12:18 p.m.

To convert a column of strings to lowercase in a Pandas DataFrame, you can use the str.lower() method. Here’s an example:

import pandas as pd

df = pd.DataFrame({'A': ['FOO', 'bAr', 'BaZ'], 'B': [4, 5, 6]}) # create a DataFrame with columns A and B
df['A'] = df['A'].str.lower() # convert the strings in column 'A' to lowercase
print(df)

Output:

     A  B
0  foo  4
1  bar  5
2  baz  6

In the example above, df['A'].str.lower() converts the column ‘A’ to lowercase using the str.lower() method. The modified DataFrame is then stored back into the original DataFrame.

If you want to convert all string columns in the DataFrame to lowercase, you can use the applymap() method:

df = pd.DataFrame({'A': ['FOO', 'bAr', 'BaZ'], 'B': ['QUX', 'quU', 'quUx']}) # create a DataFrame with columns A and B
df = df.applymap(lambda x: x.lower() if isinstance(x, str) else x) # convert all string columns to lowercase
print(df)

Output:

     A    B
0  foo  qux
1  bar  quu
2  baz  quux

In this example, the applymap() method applies a lambda function that converts strings to lowercase only if they are of type str. The modified DataFrame is then stored back into the original DataFrame.

In summary, to convert a column of strings to lowercase in a Pandas DataFrame, use the str.lower() method on the column, and store the modified DataFrame back into the original DataFrame. If you want to convert all string columns to lowercase, use the applymap() method.

Tags: