Pandas:算出自己行的值

2024-04-24 07:51:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想按组计算平均值,不考虑行本身的值。你知道吗

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是组中所有其他成员的平均值,不包括行本身的值。你知道吗


Tags: importdataframepandasdfdataasoutmean
2条回答

你可以用平均数^{}col1^{}。然后从平均值中减去给定行的值:

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

谢谢你的意见。我最终使用了@VnC链接到的方法。你知道吗

我是这样解决的:

import pandas as pd

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

group_summary = df.groupby('col1', as_index=False)['col2'].agg(['mean', 'count'])
df = pd.merge(df, group_summary, on = 'col1')

df['other_sum'] = df['col2'] * df['mean'] - df['col2'] 
df['result'] = df['other_sum'] / (df['count']  - 1)

查看最终结果:

df['result']

打印内容:

Out: 
0    1.000000
1   -0.333333
2    2.666667
3   -0.333333
4    3.000000
5    3.000000
Name: result, dtype: float64

编辑:我以前在列名方面遇到过一些问题,但是我用this答案解决了这个问题。你知道吗

相关问题 更多 >