如何从Pandas DataFrame标头中删除空格? [英] How can I strip the whitespace from Pandas DataFrame headers?

查看:1500
本文介绍了如何从Pandas DataFrame标头中删除空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析来自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:

  1. 使用inplace=True参数 [docs ]

df.rename(columns=lambda x: x.strip(), inplace=True)

  1. 将其分配回您的df变量:

df = df.rename(columns=lambda x: x.strip())

这篇关于如何从Pandas DataFrame标头中删除空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆