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 x
Note
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.
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
这是索引列,传递
index=False
不写出它,请参见docs示例:
比较:
您还可以通过传递
index_col=0
来告诉read_csv
第一列是索引列:另一种可能发生这种情况的情况是,如果您的数据不正确地写入
csv
,使每一行以逗号结尾。当您试图将数据读入df
时,这将在数据末尾留下一个未命名的列Unnamed: x
。这个问题很可能是由于CSV和它的
RangeIndex
(通常没有名称)一起保存的。在保存数据帧时,实际上需要进行修复,但这并不总是一个选项。避免问题:
read_csv
使用index_col
参数在IMO中,最简单的解决方案是将未命名的列读为索引。为^{} 指定一个
index_col=[0]
参数,这将读取第一列作为索引。权宜之计:用
str.match
过滤如果您不能修改代码来读/写CSV文件,您可以使用^{} 过滤来删除列:
相关问题 更多 >
编程相关推荐