gpt4 book ai didi

python - 如何在 pandas df 中插入第二个标题行以进行 csv 写入

转载 作者:太空宇宙 更新时间:2023-11-03 14:14:01 26 4
gpt4 key购买 nike

我有一个非常大的 pandas df,我正在写到 csv。我需要添加第二个包含数据类型的标题行。下面的代码有效,但在 CSV 中产生了第三个意外的空行:

#! /usr/bin/env python
import pandas as pd

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))

# get count of header columns, add REAL for each one
types_header_for_insert = list(df.columns.values)
for idx, val in enumerate(types_header_for_insert):
types_header_for_insert[idx] = 'REAL'

# count number of index columns, then add STRING for each one
index_count = len(df.index.names)
for idx in range(0, index_count):
df.reset_index(level=0, inplace=True)
types_header_for_insert.insert(0, 'STRING')

# insert the new types column
df.columns = pd.MultiIndex.from_tuples(zip(df.columns, types_header_for_insert))

print df.columns.values

df.to_csv("./test.csv", index=False)

输出:

index,A,B
STRING,REAL,REAL
,,
0,1,2
1,3,4

我怎样才能摆脱这个多余的空白行?它从哪里来?

最佳答案

我最后使用了一个解决方法(a)将原始标题写入 csv(b)用第二个标题行替换标题并将整个 df 附加到第一个文件:

# write the header to the file only
pd.DataFrame(data=[df.columns]).to_csv("outfile.csv", header=False, index=False)

# now replace header
types_header_for_insert = list(df.columns.values)
for idx, val in enumerate(df.columns.values):
if df[val].dtype == 'float64':
types_header_for_insert[idx] = 'REAL'

elif self.grouped[val].dtype == 'int64':
types_header_for_insert[idx] = 'INTEGER'

else:
types_header_for_insert[idx] = 'STRING'

df.columns = types_header_for_insert

# append the whole df with new header
df.to_csv("outfile.csv", mode="a", float_format='%.3f', index=False)

关于python - 如何在 pandas df 中插入第二个标题行以进行 csv 写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34956145/

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