gpt4 book ai didi

python - Pandas 到 Excel(合并标题列)

转载 作者:太空宇宙 更新时间:2023-11-03 21:27:50 25 4
gpt4 key购买 nike

我想将 df 转换为 Excel 工作表,但也想添加标题列来对所有列进行分类。 Here is a screenshot without the merged column header

and the second picture shows the 'Financials' and 'Obs' headings

用于复制:

import pandas as pd
# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Close the Pandas Excel writer and output the Excel file.
writer.save()

最佳答案

您可以创建MultiIndex:

df = pd.DataFrame({
'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
'E':[5,3,6,9,2,4],
'F':list('aaabbb')
})

指定级别的新名称以及开始和结束列名称:

L = [('OBS','A','C'), ('FIN', 'D','F')]

然后在列表理解中为 MultiIndex.from_tuples 创建元组 :

cols = [(new, c) for new, start, end in L for c in df.loc[:, start:end].columns]

print (cols)
[('OBS', 'A'), ('OBS', 'B'), ('OBS', 'C'), ('FIN', 'D'), ('FIN', 'E'), ('FIN', 'F')]

df.columns = pd.MultiIndex.from_tuples(cols)
print (df)
OBS FIN
A B C D E F
0 a 4 7 1 5 a
1 b 5 8 3 3 a
2 c 4 9 5 6 a
3 d 5 4 7 9 b
4 e 5 2 1 2 b
5 f 4 3 0 4 b

关于python - Pandas 到 Excel(合并标题列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53739458/

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