gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:38:59 41 4
gpt4 key购买 nike

我将我的数据放入 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_csv 需要一个 path_or_buf作为它的第一个参数,而不仅仅是路径名:

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

  • path_or_buf : string or file handle, default None

    File path or object, if None is provided the result is returned as a string.



下面是一个例子:
#!/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),因此如果您以后有任何问题,请随时给我留言。

关于python-2.7 - 在 pandas.DataFrame.to_csv 中写入多个标题行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27070923/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com