python - Pandas:计算平均值,忽略自己行的值

标签 python pandas mean aggregation

我想按组计算平均值,忽略行本身的值。

import pandas as pd

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

我知道如何按组返回手段:

df.groupby('col1').agg({'col2': 'mean'})

返回结果:

Out[247]: 
  col1  col2
1    a     4
3    a    -5
5    a     4

但我想要的是按组表示,省略行的值。例如。对于第一行:

df.query('col1 == "a"')[1:4].mean()

返回:

Out[251]: 
col2    1.0
dtype: float64

编辑: 预期输出是与上面的 df 格式相同的数据帧,其中 mean_excl_own 列是组中所有其他成员的平均值,不包括该行自己的值。

最佳答案

你可以GroupBy col1transform与平均值。然后从平均值中减去给定行的值:

df['col2'] = df.groupby('col1').col2.transform('mean').sub(df.col2)

关于python - Pandas:计算平均值,忽略自己行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55709649/

相关文章:

python - 共轭梯度模块中的矩阵函数

python - ValueError : Dimensions must be equal, 但分别是 512 和 256

python - 为 tf.split() 使用 num_splits 变量

python - 从数据框中删除列中的某些特定关键字并将其保存到 json

scala - 如何在 spark scala 的微风矩阵数组中找到相同单元格的平均值?

python - Groupby int 组变量和 float 值的平均值不返回任何内容

python - Python3 中的 ElementTree TypeError "write() argument must be str, not bytes"

Python PANDAS 写入 csv : how to set decimal point (".", 或 ",")?

Pandas - 延长平均 session 时间

python - 如何使用正则表达式重命名 Pandas DataFrame 的列?