我正在尝试创建一个带有小计、Excel 风格的简单数据透视表,但是我找不到使用 Pandas 的方法。我已经尝试了韦斯在另一个与小计相关的问题中建议的解决方案,但这并没有给出预期的结果。下面是重现它的步骤:
创建样本数据:
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)
Run Code Online (Sandbox Code Playgroud)
创建带有边距的数据透视表(它只有总计,没有客户 (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 …Run Code Online (Sandbox Code Playgroud)