Python csv的熊猫数据帧输出端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17134942/
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
pandas DataFrame output end of csv
提问by perigee
I wonder how to add new DataFramedata onto the end of an existing csv file? The to_csvdoesn't mention such functionality.
我想知道如何将新DataFrame数据添加到现有 csv 文件的末尾?在to_csv没有提到这样的功能。
采纳答案by Andy Hayden
You can append using to_csvby passing a file which is open in append mode:
with open(file_name, 'a') as f:
df.to_csv(f, header=False)
Use header=None, so as not to append the column names.
使用header=None,以免附加列名称。
In fact, pandas has a wrapper to do this in to_csvusing the modeargument (see Joe's answer):
实际上,pandas 有一个包装器可以to_csv使用mode参数来执行此操作(请参阅 Joe 的回答):
df.to_csv(f, mode='a', header=False)
回答by perigee
Thank to Andy, the complete solution:
感谢安迪,完整的解决方案:
f = open(filename, 'a') # Open file as append mode
df.to_csv(f, header = False)
f.close()
回答by Joe Hooper
You can also pass the file mode as an argument to the to_csv method
您还可以将文件模式作为参数传递给 to_csv 方法
df.to_csv(file_name, header=False, mode = 'a')
回答by KCzar
A little helper function I use (based on Joe Hooper's answer) with some header checking safeguards to handle it all:
我使用的一个小辅助函数(基于 Joe Hooper 的回答)和一些标题检查保护措施来处理这一切:
def appendDFToCSV_void(df, csvFilePath, sep=","):
import os
if not os.path.isfile(csvFilePath):
df.to_csv(csvFilePath, mode='a', index=False, sep=sep)
elif len(df.columns) != len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns):
raise Exception("Columns do not match!! Dataframe has " + str(len(df.columns)) + " columns. CSV file has " + str(len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns)) + " columns.")
elif not (df.columns == pd.read_csv(csvFilePath, nrows=1, sep=sep).columns).all():
raise Exception("Columns and column order of dataframe and csv file do not match!!")
else:
df.to_csv(csvFilePath, mode='a', index=False, sep=sep, header=False)

