简体   繁体   English

Pandas groupby 并计算 1/count

[英]Pandas groupby and calculate 1/count

I have a pandas dataframe like so:我有一个 pandas dataframe 像这样:

id val
1  10
1  20
2  19
2  21
2  15

Now I want to groupby id and calculate weight column as 1/count of rows in each group.现在我想按 id 分组并将权重列计算为每组中的 1/行数。 So final dataframe will be like:所以最终的 dataframe 会像:

id val weight
1  10  0.5
1  20  0.5
2  19  0.33
2  21  0.33
2  15  0.33

What's the easiest way to achieve this?实现这一目标的最简单方法是什么?

Use GroupBy.transform with division:GroupBy.transform与除法一起使用:

df['weight'] = 1 / df.groupby('id')['id'].transform('size')
#alternative
#df['weight'] = df.groupby('id')['id'].transform('size').rdiv(1)

Or Series.map with Series.value_counts :Series.mapSeries.value_counts

df['weight'] = 1 / df['id'].map(df['id'].value_counts())
#alternative
#df['weight'] = df['id'].map(df['id'].value_counts()).rdiv(1)

print (df)
   id  val    weight
0   1   10  0.500000
1   1   20  0.500000
2   2   19  0.333333
3   2   21  0.333333
4   2   15  0.333333

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

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