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
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
:
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With