使用Pandas在to_csv中添加注释

7

我将一个数据框保存到csv格式的文件中,使用的方法是to_csv,输出结果如下:

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

有人知道如何做吗?

(关于IT技术的内容,无需进一步解释)

1
为什么不直接打开文件并写入呢? - Micah Smith
你能否编辑你的帖子并添加你的数据框和脚本? - Mir Ilias
1
这是Pandas数据框吗?Pandas的to_csv函数有一个名为header的选项,默认值为True,因此您的列名应该会自动写入。 - lanenok
如@MicahSmith所说,先编写CSV,然后使用类似于这个的工具将注释添加到文件顶部。 - LondonRob
早上好,这是我找到的唯一方法:<pre><code> 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) </code></pre> - Vanessa
1个回答

8

最简单的方法是先添加注释,然后再附加数据框。以下提供了两种方法,并且在使用pandas在CSV文件中写入注释中有更多信息。

读取测试数据

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')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接