You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pandas创建带多层级列的pivot table数据透视表

问题描述

我当前的代码如下:

pd.pivot_table(filtered_dfs[key], values=["Entered Debit Amount", "Entered Credit Amount", "Converted Debit Amount", "Converted Credit Amount"],
                    index=["ATTRIBUTE1 Value for Journal Entry Line DFF", "Segment3"], aggfunc=np.sum)

这段代码运行正常,输出结果如下图所示:
当前输出示意图
但我希望将Segment3也作为分组维度放到列层级,预期实现的效果示例如下:
预期效果示意图
请问是否可以通过pandas的pivot_table功能实现上述需求?


解决方案

可以直接通过pandas的pivot_table实现该需求,只需要把原代码index参数中的Segment3移到columns参数位置即可,pivot_table原生支持行、列两个维度的分组聚合。

修改后的代码示例:

pd.pivot_table(
    filtered_dfs[key],
    values=["Entered Debit Amount", "Entered Credit Amount", "Converted Debit Amount", "Converted Credit Amount"],
    index=["ATTRIBUTE1 Value for Journal Entry Line DFF"],
    columns=["Segment3"],
    aggfunc=np.sum
)

如果希望空值位置默认显示0而不是NaN,可以额外添加fill_value=0参数:

pd.pivot_table(
    filtered_dfs[key],
    values=["Entered Debit Amount", "Entered Credit Amount", "Converted Debit Amount", "Converted Credit Amount"],
    index=["ATTRIBUTE1 Value for Journal Entry Line DFF"],
    columns=["Segment3"],
    aggfunc=np.sum,
    fill_value=0
)

内容的提问来源于stack exchange,提问作者Lê Hồng Nhật

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:24:04