【发布时间】:2014-01-07 21:22:49
【问题描述】:
我想将 pandas 数据帧附加到 CSV 文件的末尾。棘手的部分是当我追加行时,有时列可能会有所不同。我想要这样的代码
a = pd.DataFrame([[1, 2]], columns= ["one", "two"])
with open("learn.csv", "w") as f:
a.to_csv(f, header=True)
a = pd.DataFrame([[1, 2]], columns= ["one", "three"])
with open("learn.csv", "a") as f:
a.to_csv(f)
生成如下所示的 CSV 文件:
one, two, three
1, 2, None
1, None, 2
【问题讨论】:
-
最好的办法是将 DataFrame 合并为一个,并代表所有列。否则,您不仅要在 CSV 文件的“末尾”添加行,还必须返回并更改标题。
标签: python csv pandas dataframe