如何从Pandas DataFrame标头中删除空格? [英] How can I strip the whitespace from Pandas DataFrame headers?
问题描述
我正在解析来自Excel文件的数据,该文件在某些列标题中具有额外的空白.
I am parsing data from an Excel file that has extra white space in some of the column headings.
当我用df.columns
检查结果数据框的列时,我看到:
When I check the columns of the resulting dataframe, with df.columns
, I see:
Index(['Year', 'Month ', 'Value'])
^
# Note the unwanted trailing space on 'Month '
因此,我不能这样做:
df["Month"]
因为它将告诉我未找到该列,因为我要求输入月",而不是月".
Because it will tell me the column is not found, as I asked for "Month", not "Month ".
那么,我的问题是如何从列标题中去除不需要的空白?
My question, then, is how can I strip out the unwanted white space from the column headings?
推荐答案
您可以将函数赋予rename
方法. str.strip()
方法应该做您想要的.
You can give functions to the rename
method. The str.strip()
method should do what you want.
In [5]: df
Out[5]:
Year Month Value
0 1 2 3
[1 rows x 3 columns]
In [6]: df.rename(columns=lambda x: x.strip())
Out[6]:
Year Month Value
0 1 2 3
[1 rows x 3 columns]
注意:这将返回一个DataFrame
对象,并在屏幕上显示为输出,但实际上并没有在您的列上进行更改.要进行更改,请使用:
Note: that this returns a DataFrame
object and it's shown as output on screen, but the changes are not actually set on your columns. To make the changes take place, use:
- 使用
inplace=True
参数 [docs ]
df.rename(columns=lambda x: x.strip(), inplace=True)
- 将其分配回您的
df
变量:
df = df.rename(columns=lambda x: x.strip())
这篇关于如何从Pandas DataFrame标头中删除空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!