【问题标题】:Pandas: Calculate mean leaving out own row's value熊猫:计算均值忽略自己的行的值
【发布时间】: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 是组中所有其他成员的平均值,不包括行自身的值。

【问题讨论】:

标签: python pandas mean aggregation


【解决方案1】:

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

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

【讨论】:

  • 我认为 OP 想要的是组的聚合平均值而不是这个
  • 但他想从给定行中减去值,这只有在行本身包含在解决方案中时才有意义,对吧?
  • 他们想计算整个组的平均值,但忽略该组的第一行,至少这是我的理解,我当然可能是错的
  • 嗯其实我觉得你是对的,我会删除我的答案
【解决方案2】:

感谢您的所有意见。我最终使用了@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 答案修复了它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多