Pandas中多指数的百分比

时间:2018-02-09 16:59:14

标签: python python-3.x pandas

我需要找到MultiIndex列的百分比(' count')。我的DataFrame看起来像:

            count
A  week1     264

   week2      29

B  week1     152

   week2      15

我想添加一个列'百分比'制作

            count percent
A  week1     264      0.9

   week2      29      0.1

B  week1     152     0.91

   week2      15     0.09

我知道我可以通过

找到我想要的总数
mydf.sum(level=[0, 1])

但我似乎无法弄清楚如何将其转化为百分比。

2 个答案:

答案 0 :(得分:4)

您可以使用groupbytransform

执行此操作
df['percent'] = df.groupby(level=0).transform(lambda x: (x / x.sum()).round(2))

#          count  percent
# A week1    264     0.90
#   week2     29     0.10
# B week1    152     0.91
#   week2     15     0.09

答案 1 :(得分:3)

没有groupby

df['percentage']=df['count'].div(df['count'].sum(level=0),level=0)
df
Out[128]: 
         count  percentage
x b                       
A week1    264    0.901024
  week2     29    0.098976
B week1    152    0.910180
  week2     15    0.089820