这个问题很可能是由于CSV和它的RangeIndex(通常没有名称)一起保存的。在保存数据帧时,实际上需要进行修复,但这并不总是一个选项。
避免问题:read_csv使用index_col参数
在IMO中,最简单的解决方案是将未命名的列读为索引。为^{}指定一个index_col=[0]参数,这将读取第一列作为索引。df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df
a b c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
# Save DataFrame to CSV.
df.to_csv('file.csv')
pd.read_csv('file.csv')
Unnamed: 0 a b c
0 0 x x x
1 1 x x x
2 2 x x x
3 3 x x x
4 4 x x x
# Now try this again, with the extra argument.
pd.read_csv('file.csv', index_col=[0])
a b c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x xNote
You could have avoided this in the first place by
using index=False when creating the output CSV, if your DataFrame does not have an index to begin
with.df.to_csv('file.csv', index=False)
But as mentioned above, this isn't always an option.
权宜之计:用str.match过滤
如果您不能修改代码来读/写CSV文件,您可以使用^{}过滤来删除列:df
Unnamed: 0 a b c
0 0 x x x
1 1 x x x
2 2 x x x
3 3 x x x
4 4 x x x
df.columns
# Index(['Unnamed: 0', 'a', 'b', 'c'], dtype='object')
df.columns.str.match('Unnamed')
# array([ True, False, False, False])
df.loc[:, ~df.columns.str.match('Unnamed')]
a b c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x