繁体   English   中英

在 pandas.DataFrame.to_csv 中写入多个标题行

[英]Writing multiple header lines in pandas.DataFrame.to_csv

我将我的数据放入 NASA 的 ICARTT 格式以供存档。 这是一个包含多个标题行的逗号分隔文件,并且在标题行中有逗号。 就像是:

46, 1001
lastname, firstname
location
instrument
field mission
1, 1
2011, 06, 21, 2012, 02, 29
0
Start_UTC, seconds, number_of_seconds_from_0000_UTC
14
1, 1
-999, -999
measurement name, units
measurement name, units
column1 label, column2 label, column3 label, column4 label, etc.

我必须为收集数据的每一天制作一个单独的文件,因此我最终将创建大约 30 个文件。 当我通过 pandas.DataFrame.to_csv 创建一个 csv 文件时,我不能(据我所知)在写入数据之前简单地将标题行写入文件,所以我不得不欺骗它来做我想做的事情

# assuming <df> is a pandas dataframe
df.to_csv('dst.ict',na_rep='-999',header=True,index=True,index_label=header_lines)

其中“header_lines”是标题字符串

这给我的正是我想要的,除了“header_lines”用双引号括起来。 有没有办法使用 to_csv 将文本写入 csv 文件的头部或删除双引号? 我已经尝试在 to_csv() 中设置 quotechar='' 和 doublequote=False,但双引号仍然出现。

我现在正在做的(它现在有效,但我想转向更好的东西)只是通过 open('dst.ict','w') 打开一个文件并逐行打印到该文件,这是很慢。

实际上,您可以只在数据之前写入标题行。 pandas.DataFrame.to_csvpath_or_buf作为其第一个参数,而不仅仅是路径名:

pandas.DataFrame.to_csv(path_or_buf, *args, **kwargs)

  • path_or_buf : 字符串或文件句柄,默认无

    文件路径或对象,如果提供 None 则结果作为字符串返回。

下面是一个例子:

#!/usr/bin/python2

import pandas as pd
import numpy as np
import sys

# Make an example data frame.
df = pd.DataFrame(np.random.randint(100, size=(5,5)),
                  columns=['a', 'b', 'c', 'd', 'e'])

header = '\n'.join(
    # I like to make sure the header lines are at least utf8-encoded.
    [unicode(line, 'utf8') for line in 
        [ '1001',
        'Daedalus, Stephen',
        'Dublin, Ireland',
        'Keys',
        'MINOS',
        '1,1',
        '1904,06,16,1922,02,02',
        'time_since_8am', # Ends up being the header name for the index.
        ]
    ]
)

with open(sys.argv[1], 'w') as ict:
    # Write the header lines, including the index variable for
    # the last one if you're letting Pandas produce that for you.
    # (see above).
    for line in header:
        ict.write(line)

    # Just write the data frame to the file object instead of
    # to a filename. Pandas will do the right thing and realize
    # it's already been opened.
    df.to_csv(ict)

结果正是您想要的 - 编写标题行,然后调用.to_csv()并写入:

$ python example.py test && cat test
1001
Daedalus, Stephen
Dublin, Ireland
Keys to the tower
MINOS
1, 1
1904, 06, 16, 1922, 02, 02
time_since_8am,a,b,c,d,e
0,67,85,66,18,32
1,47,4,41,82,84
2,24,50,39,53,13
3,49,24,17,12,61
4,91,5,69,2,18

对不起,如果这太晚了而没有用。 我负责归档这些文件(并使用 Python),所以如果您以后有任何问题,请随时给我留言。

尽管还有几年时间并且 ndt 的回答非常好,另一种可能性是先编写标题,然后使用 to_csv() 和 mode='a' (追加):

# write the header
header = '46, 1001\nlastname, firstname\n,...'
with open('test.csv', 'w') as fp
    fp.write(header)

# write the rest
df.to_csv('test.csv', header=True, mode='a')

不过,由于两次写入操作,它的效率可能较低...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM