Python 在 Pandas 中保存 csv 时删除索引列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26786960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove index column while saving csv in pandas
提问by JPC
I'm trying to create a csvwith pandas, but when I export the data to csvit gives me an extra column
我正在尝试csv使用 Pandas创建一个,但是当我将数据导出到csv它时会给我一个额外的列
d = {'one' : pd.Series([1., 2., 3.]),'two' : pd.Series([1., 2., 3., 4.])}
df0_fa = pd.DataFrame(d)
df_csv = df0_fa.to_csv('revenue/data/test.csv',mode = 'w')
Thus, my result is:
因此,我的结果是:
,one,two
0,1.0,1.0
1,2.0,2.0
2,3.0,3.0
3,4.0,4.0
But, the expected results are:
但是,预期的结果是:
one,two
1.0,1.0
2.0,2.0
3.0,3.0
4.0,4.0
采纳答案by JD Long
What you are seeing is the index column. Just set index=False:
您看到的是索引列。只需设置index=False:
df_csv = df0_fa.to_csv('revenue/data/test.csv',mode = 'w', index=False)
回答by Revati Joshi
To read the csv file without indexing you can unset the index_col to prevent pandas from using your first column as an index. And while saving the csv back onto the disk, do not forget to set index = falsein to_csv. This will not generate an additional index column. Else, if you need to delete/remove a specific column from the data frame, use drop, it worked for me as follows :
要在没有索引的情况下读取 csv 文件,您可以取消设置 index_col 以防止熊猫使用您的第一列作为索引。虽然保存CSV放回盘,别忘了一套指数=假在to_csv。这不会生成额外的索引列。否则,如果您需要从数据框中删除/删除特定列,请使用drop,它对我有用,如下所示:
import pandas as pd
file_path = 'example_file.csv'
data_frame = pd.read_csv(file_path, index_col = False)
column_name = 'column'
data_frame = data_frame.drop(column_name, axis = 1)
data_frame.to_csv(file_path, index = False)
In this case, even if your csv has a valid index column, you can skip index_col = Falsein read_csv.
在这种情况下,即使您的CSV有一个有效的索引列,您可以跳过index_col = False在read_csv。

