用 pandas 中的最大值填充列值 [英] filling a column values with max value in pandas

查看:50
本文介绍了用 pandas 中的最大值填充列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的数据:

pd.DataFrame({'code': ['a', 'a', 'a', 'b', 'b', 'c'],
                      'value': [1,2,3, 4, 2, 1] })



+-------+------+-------+
| index | code | value |
+-------+------+-------+
| 0     | a    | 1     |
+-------+------+-------+
| 1     | a    | 2     |
+-------+------+-------+
| 2     | a    | 3     |
+-------+------+-------+
| 3     | b    | 4     |
+-------+------+-------+
| 4     | b    | 2     |
+-------+------+-------+
| 5     | c    | 1     |
+-------+------+-------+

我想添加一个包含每个代码最大值的列:

i want add a column that contain the max value of each code :

| index | code | value | max |
|-------|------|-------|-----|
| 0     | a    | 1     | 3   |
| 1     | a    | 2     | 3   |
| 2     | a    | 3     | 3   |
| 3     | b    | 4     | 4   |
| 4     | b    | 2     | 4   |
| 5     | c    | 1     | 1   |

有没有办法用熊猫来做到这一点?

is there any way to do this with pandas?

推荐答案

使用 GroupBy.transform 用于聚合值的新列:

Use GroupBy.transform for new column of aggregated values:

df['max'] = df.groupby('code')['value'].transform('max')

这篇关于用 pandas 中的最大值填充列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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