我想做以下工作。
这是我的代码。
#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而不删除当前数据?
df.to_csv()
不关心文件打开的模式,使用的是 open()
并将覆盖该文件。相反,如果要在现有的csv文件末尾添加行,你可以使用 file.wite()
方法。
# 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)