gpt4 book ai didi

python - Pandas 数据透视表可超越单独的工作表

转载 作者:行者123 更新时间:2023-12-01 09:24:51 24 4
gpt4 key购买 nike

我的 pandas 数据透视表如下所示;

Region     Dist     A     B      C
X T 1 2 0,5
X V 2 2,5 3
Z T 3 5 8,6
Y P 8,6 7,2 3
Y V 4,5 6,5 5
Z V 7 3,3 4,8
Y T 2 1,6 2,2
X P 3 3,3 2,5
Z P 5,5 6 8

所以我做了所有的计算,现在我想编写Excel用于发布,但我找不到如何按“区域”单独编写它。在本例中,它将是 3 个工作表,即 X、Y、Z,但我该如何编码呢?​​

提前致谢!

最佳答案

使用groupby用于按 ExcelWriter 的组循环:

with pd.ExcelWriter('file.xlsx') as writer:
df.groupby('Region').apply(lambda x: x.to_excel(writer, sheet_name=x.name, index=False))

替代方案:

with pd.ExcelWriter('file.xlsx') as writer:
for i, x in df.groupby('Region'):
x.to_excel(writer, sheet_name=i, index=False)

如果需要删除输出中的Region 列:

with pd.ExcelWriter('file.xlsx') as writer:
for i, x in df.groupby('Region'):
x.drop('Region', axis=1).to_excel(writer, sheet_name=i, index=False)

关于python - Pandas 数据透视表可超越单独的工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50510865/

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