简体   繁体   中英

Pandas groupby and calculate 1/count

I have a pandas dataframe like so:

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. So final dataframe will be like:

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:

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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