我想按组计算平均值,忽略行本身的值。
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
Edit:预期输出是格式相同的数据帧df
上面有一个列mean_excl_own
这是组中所有其他成员的平均值,不包括行本身的值。