如何将pandas数据添加到现有的csv文件? [英] How to add pandas data to an existing csv file?

查看:440
本文介绍了如何将pandas数据添加到现有的csv文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用pandas to_csv()函数将数据帧添加到现有的csv文件。 csv文件具有与加载的数据相同的结构。

I want to know if it is possible to use the pandas to_csv() function to add a dataframe to an existing csv file. The csv file has the same structure as the loaded data.

提前感谢

推荐答案

/ em>添加到csv,方法是以附加模式打开文件

You can append to a csv by opening the file in append mode:

with open('my_csv.csv', 'a') as f:
    df.to_csv(f, header=False)

如果这是您的csv, foo.csv

If this was your csv, foo.csv:

,A,B,C
0,1,2,3
1,4,5,6

如果你读过,然后附加,例如 df + 6

If you read that and then append, for example, df + 6:

In [1]: df = pd.read_csv('foo.csv', index_col=0)

In [2]: df
Out[2]:
   A  B  C
0  1  2  3
1  4  5  6

In [3]: df + 6
Out[3]:
    A   B   C
0   7   8   9
1  10  11  12

In [4]: with open('foo.csv', 'a') as f:
             (df + 6).to_csv(f, header=False)

foo.csv 变为:

,A,B,C
0,1,2,3
1,4,5,6
0,7,8,9
1,10,11,12

这篇关于如何将pandas数据添加到现有的csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆