深度阅读

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

作者
作者
2023年08月22日
更新时间
15.1 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。