【问题标题】:How to append to csv file without creating multiple copies of headers into rows?如何在不将多个标题副本创建到行中的情况下附加到 csv 文件?
【发布时间】:2020-08-12 14:30:14
【问题描述】:

我正在尝试将 Dataframe 写入 csv

for i in range 10:
    consolidated_df.to_csv(output_file_path + '/' +   dest_csv,mode='a',index=False)

这是为每次迭代创建添加标题作为新行

col1 col2 col3
a     b     c
col1 col2  col3
d    e      f
col  col2   col3
g    h      i

如果我在 df.to_csv 中使用 header=none ,那么 csv 根本没有任何标题

我只需要这个

col1 col2 col3
a     b     c
d    e      f
g    h      i

【问题讨论】:

    标签: python python-3.x dataframe csv


    【解决方案1】:

    一种方法是检查索引是否为 0,然后添加标头,否则将标头设置为无

    例如:

    for i in range(10):
        if i == 0:
            consolidated_df.to_csv(output_file_path + '/' +  dest_csv,mode='a',index=False)
        else:
            consolidated_df.to_csv(output_file_path + '/' +  dest_csv,mode='a',index=False, header=None)
    

    【讨论】:

      猜你喜欢
      • 2017-06-18
      • 1970-01-01
      • 2020-08-04
      • 2022-12-24
      • 2014-11-15
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      • 2017-11-26
      相关资源
      最近更新 更多