python - 取组中的最大值,忽略当前行的值

标签 python pandas max

我想计算组中的最大值,但不使用该行自己的值。

所以如果我们有一个像这样的数据框:

d = {'col1': ["a", "a", "b", "a", "b", "a"], 'col2': [0, 4, 3, -5, -1, 2]}
df = pd.DataFrame(data=d)

print(df)

  col1  col2
0    a     0
1    a     4
2    b     3
3    a    -5
4    b    -1
5    a     2

然后我想添加一列max_other,如下所示:

  col1  col2 max_other
0    a     0    4
1    a     4    2
2    b     3    -1
3    a    -5    4
4    b    -1    3
5    a     2    4

来源:这是 this 的后续问题我询问了有关计算组中的均值而忽略了行自身值的问题。

编辑:我的 max_other 在第 1 行有一个错误(它说的是 3,而实际上应该是 2)。

最佳答案

你可以尝试:

m=df.groupby('col1')['col2'].transform(lambda x: x.eq(x.max()))
d1=df[~m].groupby('col1')['col2'].max().to_dict()
d2=dict(zip(df.loc[m,'col1'],df.loc[m,'col2']))
<小时/>
df['max_other']=np.where(m,df.col1.map(d1),df.col1.map(d2))
print(df)

  col1  col2  max_other
0    a     0          4
1    a     4          2
2    b     3         -1
3    a    -5          4
4    b    -1          3
5    a     2          4

详细信息: 我们创建一个 bool 掩码来检查该行是否等于该组的最大值:

m=df.groupby('col1')['col2'].transform(lambda x: x.eq(x.max()))
print(m)

0    False
1     True
2     True
3    False
4    False
5    False

我们创建 2 个字典:

print(d1)
{'a': 2, 'b': -1}

print(d2)
{'a': 4, 'b': 3}

然后我们使用 np.where()查看条件匹配的位置和不匹配的位置,并进行相应的映射。

关于python - 取组中的最大值,忽略当前行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55723828/

相关文章:

python - python有没有可以可视化方法和类的工具?

java - 如何找到该学生数组中所有学生的最高、最低和总平均数

r - 将 MIN 和 MAX 组合成 R 中的 rowise 函数

MYSQL选择当前连续获胜

python - 将 request.user 参数传递给 modelformset_factory 表单

参数中的python列表

python - Zipline - csv 文件

python - DataFrame 性能警告

python - 处理标签编码的未知值

python - AssertionError : The field ' ' was declared on serializer ' ' ,,但尚未包含在 'fields'选项中