我想执行以下操作:
这是我的代码:
#create a file if does not exist
import numpy as np
import pandas as pd
myseries=pd.Series(np.random.randn(5))
os.chdir(r"G:\..")
file = open('test.csv', 'a+')
df = pd.DataFrame(myseries, columns=['values'])
df.to_csv("test.csv" , index=False)
-----------------
# merge with data.csv
-------------
# create a file if does not exist, if exist write new values without overwritting the existing ones
myseries=pd.Series(np.random.randn(5))
os.chdir(r"G:\..")
file = open('test.csv', 'a+')
df = pd.DataFrame(myseries, columns=['values'])
df.to_csv("test.csv" , index=False)
# the values after merge were deleted and replaced with the new data
我尝试了a,a +,w,w +,但是文件中的当前数据被新的替换了。 如何定义将新数据写入csv而不删除当前数据?
答案 0 :(得分:1)
df.to_csv()
并不关心使用open()
打开文件的方式,并且无论如何都会覆盖文件。您可以使用file.wite()
方法,而不是在现有的csv文件的末尾附加行。
# For concatenation, remove the headers or they will show up as a row
contents = df.to_csv(index = False, header=False)
file = open("test.csv",'a')
file.write(contents)
file.close()
或者您可以读取,合并并重写文件
test = pd.read_csv('test.csv')
test = pd.concat([test, df])
test.to_csv('test.csv',index=False)
要追加列,可以将轴设置为1。
test = pd.read_csv('test.csv')
test = pd.concat([test, df], axis=1)
test.to_csv('test.csv',index=False)