【发布时间】:2019-09-06 15:26:58
【问题描述】:
我想按组计算均值,省略行本身的值。
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 是组中所有其他成员的平均值,不包括行自身的值。
【问题讨论】:
-
df.groupby('col1').mean()
标签: python pandas mean aggregation