使用熊猫添加带有“ to_csv”的注释

Van*_*ssa 5 python pandas

我使用方法保存一个数据框,to_csv输出如下所示:

2015 04 08 0.0 14.9
2015 04 09 0.0  9.8
2015 04 10 0.3 23.0
Run Code Online (Sandbox Code Playgroud)

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

#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
Run Code Online (Sandbox Code Playgroud)

有谁知道这是怎么做到的吗?

joe*_*lom 5

最简单的方法是先添加注释,然后附加数据框。下面给出了两种方法,在使用 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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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')
Run Code Online (Sandbox Code Playgroud)