加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

使用pandas在“to_csv”中添加注释

发布时间:2020-12-20 13:51:18 所属栏目:Python 来源:网络整理
导读:我用方法to_csv保存一个数据帧,输出是这样的: 2015 04 08 0.0 14.92015 04 09 0.0 9.82015 04 10 0.3 23.0 但我需要对此输出进行一些修改,我需要添加一个注释和一个具有常量值和与其他列相同大小的列.我需要获得像这样的输出: #Data from the ...#yyyy mm
我用方法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 commentn')
    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 commentn')
iris.to_csv('test2.csv',mode='a')

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读