【发布时间】:2020-10-17 16:31:45
【问题描述】:
我正在尝试使用 Excel 样式的小计创建一个简单的数据透视表,但是我找不到使用 Pandas 的方法。我已经尝试过 Wes 在另一个与小计相关的问题中建议的解决方案,但这并没有给出预期的结果。下面是重现它的步骤:
创建示例数据:
sample_data = {'customer': ['A', 'A', 'A', 'B', 'B', 'B', 'A', 'A', 'A', 'B', 'B', 'B'], 'product': ['astro','ball','car','astro','ball', 'car', 'astro', 'ball', 'car','astro','ball','car'],
'week': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
'qty': [10, 15, 20, 40, 20, 34, 300, 20, 304, 23, 45, 23]}
df = pd.DataFrame(sample_data)
创建带有边距的数据透视表(它只有总计,没有客户(A,B)的小计)
piv = df.pivot_table(index=['customer','product'],columns='week',values='qty',margins=True,aggfunc=np.sum)
week 1 2 All
customer product
A astro 10 300 310
ball 15 20 35
car 20 304 324
B astro 40 23 63
ball 20 45 65
car 34 23 57
All 139 715 854
然后,我尝试了Wes Mckiney在另一个线程中提到的方法,使用stack函数:
piv2 = df.pivot_table(index='customer',columns=['week','product'],values='qty',margins=True,aggfunc=np.sum)
piv2.stack('product')
结果具有我想要的格式,但带有“全部”的行没有总和:
week 1 2 All
customer product
A NaN NaN 669.0
astro 10.0 300.0 NaN
ball 15.0 20.0 NaN
car 20.0 304.0 NaN
B NaN NaN 185.0
astro 40.0 23.0 NaN
ball 20.0 45.0 NaN
car 34.0 23.0 NaN
All NaN NaN 854.0
astro 50.0 323.0 NaN
ball 35.0 65.0 NaN
car 54.0 327.0 NaN
如何使它像在 Excel 中一样工作,示例如下?所有小计和总计工作?我错过了什么?编 excel sample
只是指出,我可以在每次迭代时使用客户的 For 循环过滤并稍后连接,但我希望可能有更直接的解决方案,谢谢
【问题讨论】:
标签: python pandas pivot-table pandas-groupby