This question already has answers here:
Write comments in CSV file with pandas

(2个答案)


2年前关闭。




我使用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

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

最佳答案

最简单的方法是先添加注释,然后附加数据框。下面给出了两种解决方法,并且在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')

关于python - 使用 Pandas 使用 "to_csv"添加评论,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31254050/

10-11 22:48
查看更多