【发布时间】:2016-09-06 00:53:42
【问题描述】:
给定以下数据框和数据透视表:
import pandas as pd
df=pd.DataFrame({'A':['x','y','z','x','y','z'],
'B':['one','one','one','two','two','two'],
'C':[2,18,2,8,2,18]})
df
A B C
0 x one 2
1 y one 18
2 z one 2
3 x two 8
4 y two 2
5 z two 18
table = pd.pivot_table(df, index=['A', 'B'],aggfunc=np.sum)
C
A B
x one 2
two 8
y one 18
two 2
z one 2
two 18
我想在此数据透视表中添加 2 列;一个显示所有值的百分比,另一个显示 A 列中的百分比,如下所示:
C % of Total % of B
A B
x one 2 4% 10%
two 18 36% 90%
y one 2 4% 20%
two 8 16% 80%
z one 2 4% 10%
two 18 36% 90%
额外积分:
我想要一个底部汇总行,其中包含 C 列的总和(如果接下来的 2 列也有 100% 也可以,但不需要这些)。
【问题讨论】:
标签: python-3.x pandas pivot-table percentage