简体   繁体   English

Pandas中多指数的百分比

[英]Percentage of a multiindex in Pandas

I need to find the percentage of a MultiIndex column ('count'). 我需要找到MultiIndex列的百分比('count')。 My DataFrame looks like: 我的DataFrame看起来像:

            count
A  week1     264

   week2      29

B  week1     152

   week2      15

and I'd like to add a column 'percent' to make 我想添加一个列“百分比”来制作

            count percent
A  week1     264      0.9

   week2      29      0.1

B  week1     152     0.91

   week2      15     0.09

I know that I can find the totals I want by 我知道我可以找到我想要的总数

mydf.sum(level=[0, 1])

but I can't seem to figure out how to turn this into a percentage. 但我似乎无法弄清楚如何将其转化为百分比。

You can do this with groupby and transform : 你可以用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

Without groupby 没有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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM