创建一个包含小计的数据透视表,并在Python Pandas中获取父总数的百分比

时间:2017-10-24 11:14:01

标签: python pandas

我可以在python pandas中创建一个数据透视表,但是无法获得小计。我得到了总列总数和总行数,但没有得到总数。

Ex:如果我在Python中创建的数据透视图如下,我想得到BU:A和Region:APAC的小计。同样,BU的小计:A和地区:欧盟等。请帮忙。

表:

BU  Region   Level  Jan      Feb      Mar
A    APAC     1     value    value    value
              2     value    value    value
              3     value    value    value
     EU       1     value    value    value
              2     value    value    value
              3     value    value    value
     NA       1     value    value    value
              2     value    value    value
              3     value    value    value
B    APAC     1     value    value    value
              2     value    value    value
              3     value    value    value
     EU       1     value    value    value
              2     value    value    value
              3     value    value    value
     NA       1     value    value    value
              2     value    value    value
              3     value    value    value

1 个答案:

答案 0 :(得分:1)

使用groupby和pd.concat而不是数据透视表,即

x = df.groupby(level=['BU','Region']).apply(sum).assign(Level='Total')
# if BU and Region is not index then use df.groupby(['BU,'Region'])...
# if the values are numbers then `.sum()` than `.apply(sum)`
ndf = pd.concat([df,x]).sort_index()

输出:  

          Level              Jan              Feb              Mar
BU Region
A APAC 1 value value value APAC 2 value value value APAC 3 value value value APAC Total valuevaluevalue valuevaluevalue valuevaluevalue EU 1 value value value EU 2 value value value EU 3 value value value EU Total valuevaluevalue valuevaluevalue valuevaluevalue NaN 1 value value value NaN 2 value value value NaN 3 value value value B APAC 1 value value value APAC 2 value value value APAC 3 value value value APAC Total valuevaluevalue valuevaluevalue valuevaluevalue EU 1 value value value EU 2 value value value EU 3 value value value EU Total valuevaluevalue valuevaluevalue valuevaluevalue NaN 1 value value value NaN 2 value value value NaN 3 value value value