pandas 非常简单来自分组依据的总大小的百分比 [英] Pandas Very Simple Percent of total size from Group by
问题描述
我在看似非常简单的操作上遇到了麻烦.最简洁的方法是通过诸如df.groupby['col1'].size()
之类的操作从一个组中获得总数的百分比.分组后我的DF看起来像这样,我只想占总数的百分之一.我记得以前使用过此语句的变体,但现在无法使它起作用:percent = totals.div(totals.sum(1), axis=0)
I'm having trouble for a seemingly incredibly easy operation. What is the most succint way to just get a percent of total from a group by operation such as df.groupby['col1'].size()
. My DF after grouping looks like this and I just want a percent of total. I remember using a variation of this statement in the past but cannot get this to work now: percent = totals.div(totals.sum(1), axis=0)
原始DF:
A B C
0 77 3 98
1 77 52 99
2 77 58 61
3 77 3 93
4 77 31 99
5 77 53 51
6 77 2 9
7 72 25 78
8 34 41 34
9 44 95 27
结果:
df1.groupby('A').size() / df1.groupby('A').size().sum()
A
34 0.1
44 0.1
72 0.1
77 0.7
到目前为止,这是我想出的方法,这似乎很合理:
Here is what I came up with so far which seems pretty reasonable way to do this:
df.groupby('col1').size().apply(lambda x: float(x) / df.groupby('col1').size().sum()*100)
推荐答案
通过使用以下方法在形状为(3e6,59)的DF上获得良好的性能(3.73s):
df.groupby('col1').size().apply(lambda x: float(x) / df.groupby('col1').size().sum()*100)
Getting good performance (3.73s) on DF with shape (3e6,59) by using:
df.groupby('col1').size().apply(lambda x: float(x) / df.groupby('col1').size().sum()*100)
这篇关于 pandas 非常简单来自分组依据的总大小的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!