深度阅读

How to remove leading/trailing white spaces in pandas?

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

To remove leading/trailing white spaces from column names in pandas, you can use the str.strip() method on the column names. Here’s an example:

import pandas as pd

# create a sample dataframe
df = pd.DataFrame({' Column A ': [1, 2, 3], ' Column B ': ['a', 'b', 'c']})

# strip leading/trailing spaces from column names
df.columns = df.columns.str.strip()

print(df)

This will output the DataFrame with the column names stripped of any leading or trailing spaces:

   Column A Column B
0         1        a
1         2        b
2         3        c

Note that str.strip() returns a new object with the spaces removed, it does not modify the original object in place. Additionally, the str.strip() method only works on string columns, so if you have columns with non-string data types, you may need to convert them to strings first or use a different method to remove the spaces.

相关标签

博客作者

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