我想将 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
最佳答案
您必须在保存到 csv 之前连接您的数据框,因为您必须知道所有结果列才能正确保存数据,而这对于每个数据框来说都是未知的。以下将做:
>>> from StringIO import StringIO
>>> buf = StringIO()
>>> a = pd.DataFrame([[1, 2]], columns= ["one", "two"])
>>> b = pd.DataFrame([[1, 2]], columns= ["one", "three"])
>>> pd.concat([a, b]).to_csv(buf, index=None, na_rep='None')
>>> print buf.getvalue()
one,three,two
1,None,2.0
1,2.0,None
关于python - Pandas 数据帧到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20982165/