将Pandas Groupby结果合并回DataFrame [英] Merging a pandas groupby result back into DataFrame

查看:223
本文介绍了将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

这篇关于将Pandas Groupby结果合并回DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆