【问题标题】:adding a comment with "to_csv" using pandas [duplicate]使用熊猫添加带有“to_csv”的评论[重复]
【发布时间】:2015-09-24 02:01:03
【问题描述】:

我用to_csv的方法保存了一个dataframe,输出是这样的:

2015 04 08 0.0 14.9
2015 04 09 0.0  9.8
2015 04 10 0.3 23.0

但我需要对此输出进行一些修改,我需要添加一个注释和一个具有恒定值且与其他列大小相同的列。我需要获得这样的输出:

#Data from the ...
#yyyy mm dd pcp temp er
2015 04 08 0.0 14.9 0
2015 04 09 0.0  9.8 0
2015 04 10 0.3 23.0 0

有人知道怎么做吗?

【问题讨论】:

  • 为什么不只是open 文件并写入它?
  • 您可以编辑您的帖子并添加您的数据框和脚本吗?
  • 是熊猫数据框吗? pandas to_csv 有选项header,默认为True,所以你的列名应该自动写入
  • 正如@MicahSmith 所说,先编写CSV,然后使用this 之类的内容将注释添加到文件顶部。
  • 早上好,这是我找到的唯一方法:
     line="#GEO \n#lat long level date time value \n#DATA\n" with open(Filename , 'w') as f: f.write(line) df1.to_csv(auxiliar, index = False, sep='\t', float_format='%.6f', header = False) with open(nombreFichero, 'a ') as f: with open(auxiliar, 'rb') as g: shutil.copyfileobj(g, f) 

标签: python pandas


【解决方案1】:

最简单的方法是先添加注释,然后附加数据框。下面给出了两种方法,Write comments in CSV file with pandas 中有更多信息。

读入测试数据

import pandas as pd
# Read in the iris data frame from the seaborn GitHub location
iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
# Create a bigger data frame
while iris.shape[0] < 100000:
    iris = iris.append(iris)
# `iris.shape` is now (153600, 5)

1。附加相同的文件处理程序

# Open a file in append mode to add the comment
# Then pass the file handle to pandas
with open('test1.csv', 'a') as f:
    f.write('# This is my comment\n')
    iris.to_csv(f)

2。使用to_csv(mode='a') 重新打开文件

# Open a file in write mode to add the comment
# Then close the file and reopen it with pandas in append mode
with open('test2.csv', 'w') as f:
    f.write('# This is my comment\n')
iris.to_csv('test2.csv', mode='a')

【讨论】:

    【解决方案2】:

    如果这确实是pandas 数据框,则必须自动保存列名,输入以下内容进行检查:

    print df.columns 
    

    其中df 是您的pd.DataFrame() 的名称

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 2021-05-31
      • 2016-07-06
      • 2016-01-17
      • 1970-01-01
      • 2018-05-16
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多