将Pandas Groupby结果合并回DataFrame

将Pandas Groupby结果合并回DataFrame

问题描述:

我有一个看起来像这样的DataFrame ...

I have a DataFrame that looks like this...

   idn value  
0  ID1    25
1  ID1    30
2  ID2    30
3  ID2    50

我想在此框架中添加另一列,即"idn"分组的最大值"

I want to add another column to this frame that is the max 'value' grouped by 'idn'

我想要一个看起来像这样的结果.

I want a result that looks like this.

   idn value  max_val
0  ID1    25       30
1  ID1    30       30
2  ID2    30       50
3  ID2    50       50

我可以像这样用一个组来提取'value'的最大值...

I can extract the max of 'value' using a group by like so...

df[['idn', 'value']].groupby('idn')['value'].max()

但是,我无法将结果合并回原始DataFrame中.

However, I am unable to merge that result back into the original DataFrame.

获得理想结果的最佳方法是什么?

What is the best way to get the desired result?

谢谢

对groupby对象使用transform方法:

Use the transform method on a groupby object:

In [5]: df['maxval'] = df.groupby(by=['idn']).transform('max')

In [6]: df
Out[6]: 
   idn  value  maxval
0  ID1     25      30
1  ID1     30      30
2  ID2     30      50
3  ID2     50      50