我正在解析Excel文件中的数据,该文件在某些列标题中有额外的空白区域.
当我检查结果数据帧的列时,如下所示:
df.columns
结果如下:
Index(['Year', 'Month ', 'Value'])
因此,我无法逃避
df["Month"]
因为它会告诉我找不到列,因为我要求"月",而不是"月".
那么,我的问题是如何从列标题中删除不需要的空白区域?
Tom*_*ger 105
您可以为该rename
方法提供函数.该str.strip()
方法应该做你想要的.
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]
Run Code Online (Sandbox Code Playgroud)
EdC*_*ica 52
.str.strip
如果您使用的是最新版本,现在可以调用列:
In [5]:
df = pd.DataFrame(columns=['Year', 'Month ', 'Value'])
print(df.columns.tolist())
df.columns = df.columns.str.strip()
df.columns.tolist()
['Year', 'Month ', 'Value']
Out[5]:
['Year', 'Month', 'Value']
Run Code Online (Sandbox Code Playgroud)
计时
In[26]:
df = pd.DataFrame(columns=[' year', ' month ', ' day', ' asdas ', ' asdas', 'as ', ' sa', ' asdas '])
df
Out[26]:
Empty DataFrame
Columns: [ year, month , day, asdas , asdas, as , sa, asdas ]
%timeit df.rename(columns=lambda x: x.strip())
%timeit df.columns.str.strip()
1000 loops, best of 3: 293 µs per loop
10000 loops, best of 3: 143 µs per loop
Run Code Online (Sandbox Code Playgroud)
所以str.strip
速度提高约2倍,我希望这能够更好地扩展到更大的dfs
Eri*_*nil 13
如果使用 CSV 格式从 Excel 导出并读取为 Pandas DataFrame,则可以指定:
skipinitialspace=True
Run Code Online (Sandbox Code Playgroud)
打电话时pd.read_csv
。
从文档:
skipinitialspace : bool,默认为 False
Run Code Online (Sandbox Code Playgroud)Skip spaces after delimiter.