大熊猫分组百分比

时间:2016-09-08 10:41:51

标签: python pandas group-by percentage

如何计算熊猫中的分组百分比?

类似于 Pandas: .groupby().size() and percentagesPandas Very Simple Percent of total size from Group by我想计算每组价值的百分比。

我怎样才能做到这一点?

我的数据集结构类似于

ClassLabel, Field

最初,我在ClassLbelField上聚合,如

grouped = mydf.groupby(['Field', 'ClassLabel']).size().reset_index()
grouped = grouped.rename(columns={0: 'customersCountPerGroup'})

现在,我想知道每组中每组客户的百分比。可以像mydf.groupby(['Field']).size()那样获得组总数,但是我既不能将其合并为列,也不确定这是正确的方法 - 必须有更简单的方法。

修改

我想仅根据单个组计算百分比,例如3 0 0.125 1 0.250 0 + 1的总和 - > 0.125 + 0.250 = 0,375并使用此值来分组/标准化分组而不是分组.sum() enter image description here

1 个答案:

答案 0 :(得分:4)

您可以使用的IIUC:

mydf = pd.DataFrame({'Field':[1,1,3,3,3],
                   'ClassLabel':[4,4,4,4,4],
                   'A':[7,8,9,5,7]})

print (mydf)
   A  ClassLabel  Field
0  7           4      1
1  8           4      1
2  9           4      3
3  5           4      3
4  7           4      3

grouped = mydf.groupby(['Field', 'ClassLabel']).size()
print (grouped)
Field  ClassLabel
1      4             2
3      4             3
dtype: int64

print (100 * grouped / grouped.sum())
Field  ClassLabel
1      4             40.0
3      4             60.0
dtype: float64
grouped = mydf.groupby(['Field', 'ClassLabel']).size().reset_index()
grouped = grouped.rename(columns={0: 'customersCountPerGroup'})
print (grouped)
   Field  ClassLabel  customersCountPerGroup
0      1           4                       2
1      3           4                       3

grouped['per'] = 100 * grouped.customersCountPerGroup / grouped.customersCountPerGroup.sum()
print (grouped)
   Field  ClassLabel  customersCountPerGroup   per
0      1           4                       2  40.0
1      3           4                       3  60.0

通过评论编辑:

mydf = pd.DataFrame({'Field':[1,1,3,3,3,4,5,6],
                   'ClassLabel':[0,0,0,1,1,0,0,6],
                   'A':[7,8,9,5,7,5,6,4]})

print (mydf)

grouped = mydf.groupby(['Field', 'ClassLabel']).size()
df =  grouped / grouped.sum()

df = (grouped / df.groupby(level=0).transform('sum')).reset_index(name='new')
print (df)
   Field  ClassLabel       new
0      1           0  8.000000
1      3           0  2.666667
2      3           1  5.333333
3      4           0  8.000000
4      5           0  8.000000
5      6           6  8.000000