pandas 将pandas数据帧逐行写入csv文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46090719/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:24:46  来源:igfitidea点击:

Write pandas dataframe to csv file line by line

pythonpandas

提问by Hyman west

I'm trying to write a pandas dataframe to a CSV file with the associated headers in tact row by row. I've accomplished this using

我正在尝试将一个 Pandas 数据帧写入一个 CSV 文件,并逐行将相关的标题巧妙地写入一个 CSV 文件中。我已经完成了这个使用

    new_df = pd.DataFrame(old_df).T

Which appears to produce a format (I think a dict?) where I can then write to a csv file line by line using the following

这似乎产生了一种格式(我认为是 dict?),然后我可以使用以下内容逐行写入 csv 文件

    with open('new.csv', 'a') as f:
        new_df.to_csv(f)

However in the CSV file I have two new columns both with incremental numbers (1,2,3..) for each row. The second column has the key 'Unnamed: 0' while the first column has no key (i.e. key = '').

但是,在 CSV 文件中,我有两个新列,每行都有增量编号 (1,2,3..)。第二列的键是“Unnamed: 0”,而第一列没有键(即键 = '')。

I would prefer to not have these headers, I can delete the second on using

我宁愿没有这些标题,我可以删除第二个使用

del new_df['Unnamed: 0']

but I can't do this for the second as it has no key (del new_df[''] does not work).

但第二次我不能这样做,因为它没有键(del new_df[''] 不起作用)。

Would anyone know either how to delete the first column or a better way to write a dataframe to a csv file row by row..

有谁知道如何删除第一列或将数据帧逐行写入 csv 文件的更好方法。

回答by jezrael

It seems you need parameter index=Falsefor not write first column called index (0,1,2...) and header=Falsefor no columns names:

似乎您需要参数index=False来不写入名为 index ( 0,1,2...) 的第一列并且header=False没有列名:

df.to_csv('file', index=False, header=False)