【问题标题】:Pandas DataFrame to CSV熊猫数据框到 CSV
【发布时间】: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


【解决方案1】:

您必须在保存到 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

【讨论】:

    【解决方案2】:

    这是我使用 alko 的帖子和上面的评论得出的答案。 “a”是数据框:

    if not os.path.isfile("learn.csv"):
        with open("learn.csv", "w") as f:
            a.to_csv(f, header=True, index=False)
    else:
        reader = csv.reader(open("learn.csv"))
        csv_col = set(reader.next())
        games_col = set(list(a.columns))
        if csv_col.issuperset(games_col):
            with open("learn.csv", "a") as f:
                a.to_csv(f, header=False, index=False)
        else:
            old_entries = pd.read_csv('learn.csv')
            all_entries = pd.concat([old_entries, a])
            with open("learn.csv", "w") as f:
                all_entries.to_csv(f, header=True, index=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-25
      • 2020-06-03
      • 1970-01-01
      • 2019-09-30
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 2014-03-28
      相关资源
      最近更新 更多