本文介绍了多索引 Pandas 数据框并在 excel 中导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个多索引数据框:
I have this multi-index dataframe:
Value
Year 2010 2011 2012 2013 2014 2015 2016 2017 2018
Partner Product Reporter
FRA 111 ARG 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
ARM 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
AUT 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
BEL 0.01 0.00 0.00 0.00 0.00 0.01 0.01 0.01 0.0
BGR 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
CAN 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
112 ARG 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
ARM 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
AUT 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
BEL 0.01 0.00 0.00 0.00 0.00 0.01 0.01 0.01 0.0
BGR 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
CAN 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
... ... ... ... ... ... ... ... ... ... ...
9900 OMN 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
PAK 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
PAN 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
PER 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
PHL 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.0
它包括合作伙伴"列中的 1 个元素和产品"列中的 444 个元素(所有这些元素都包含在名为产品"的列表中).我需要为任何产品创建 444 个数据帧(可能带有 for cicle)并将它们保存在一个 excel 文件中(如果有人在不同的工作表中更好).你能帮我吗?
It includes 1 element in column "Partner" and 444 element in column "Product" (all those elements are included in a list called "Products").I need to create 444 dataframes (maybe with a for cicle) for any product and save them in an excel file (better if anyone in different sheets).May you help me?
推荐答案
想法是使用 ExcelWriter
并通过 groupby
循环创建新工作表:
Idea is use ExcelWriter
and create new sheets in loop by groupby
:
with pd.ExcelWriter('output.xlsx') as writer:
for i, g in df.sort_index(level=1, ascending=False).groupby(level=1, sort=False):
g.to_excel(writer, sheet_name=f'Sheet_name_{i}')
这篇关于多索引 Pandas 数据框并在 excel 中导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!