我使用方法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
有谁知道怎么做?
答案 0 :(得分:2)
最简单的方法是先添加注释,然后附加数据框。下面给出了两种方法,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)
# 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)
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')
答案 1 :(得分:-1)
如果确实是pandas
数据框,则必须自动保存列名称,请键入以下内容进行检查:
print df.columns
其中df
是pd.DataFrame()