pandas 中的多索引百分比 [英] Percentage of a multiindex in Pandas
本文介绍了 pandas 中的多索引百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要找到MultiIndex列的百分比(计数").我的DataFrame看起来像:
I need to find the percentage of a MultiIndex column ('count'). My DataFrame looks like:
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
我知道我可以通过
mydf.sum(level=[0, 1])
但我似乎无法弄清楚如何将其转换为百分比.
but I can't seem to figure out how to turn this into a percentage.
推荐答案
您可以使用groupby
和transform
:
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
这篇关于 pandas 中的多索引百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文