如何使用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
相关产品推荐
相关产品推荐

