【问题标题】:In Pandas, how to apply a customized function using Group mean on Groupby Object在 Pandas 中,如何在 Groupby 对象上使用 Group mean 应用自定义函数
【发布时间】:2016-03-23 12:57:30
【问题描述】:

这是我的输入数据。

df1= pd.DataFrame( np.random.randn(10,3), columns= list("ABC") )

      A         B         C
0  0.557303  1.657976 -0.091638
1 -0.769201  1.305553 -0.248403
2  1.251513 -0.634947  0.100130
3 -1.030045 -0.268972  1.328666
4  0.665483 -0.133410  0.151235
5  0.703294 -0.525490  0.109413
6  0.549441  0.002626 -0.005841
7  0.454866  1.094490 -1.946760
8 -0.152995 -0.736689 -0.367252
9 -0.632906  1.066869  0.303271

我想根据 A 列的值创建组。所以我首先对 A 进行切片。并定义一个函数。然后我在 Groupby Obj 上使用 apply 方法。我期望新列是 B 和 C 与 A 的组平均值之间的差异。

b=np.linspace(-1, 1,5)

def tmpF(x):
  x['newCol']= (x['B']-x['C'])/df1['A'].mean()
return x

df1.groupby(np.digitize(df1['A'],b)).apply(tmpF)

但是,我只使用整个 A 列的平均值。我知道 df1['A'].mean() 是错误的,但我不知道如何访问组均值。 怎么解决?

【问题讨论】:

  • 我试过了。它失败并出现错误“ValueError: Buffer has wrong number of dimensions (expected 1, got 2).”
  • 谢谢。有用 !!!它失败了,只是因为我的一个愚蠢的错字。我使用 np.digitize(df1,b) 而不是 df1['A']。它会导致尺寸问题。
  • 是的,你解决了。答案很有帮助。

标签: python pandas


【解决方案1】:

您可以在函数tmpF中将df1['A']更改为x['A']

b=np.linspace(-1, 1,5)

def tmpF(x):
  x['newCol']= (x['B']-x['C'])/x['A'].mean()
return x

df1.groupby(np.digitize(df1['A'],b)).apply(tmpF)

【讨论】:

    猜你喜欢
    • 2021-10-01
    • 2023-01-23
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2014-07-16
    • 1970-01-01
    相关资源
    最近更新 更多