我想按组计算平均值,忽略行本身的值。
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
col1
和 transform
与平均值。然后从平均值中减去给定行的值:
df['col2'] = df.groupby('col1').col2.transform('mean').sub(df.col2)
关于python - Pandas:计算平均值,忽略自己行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55709649/