Skip to main content
 首页 » 编程设计

python之在 Pandas 中,如何在 Groupby 对象上使用 Group mean 应用自定义函数

2025年05月04日14telwanggs

这是我的输入数据。

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() 是错误的,但我不知道如何访问组平均值。 如何解决?

请您参考如下方法:

您可以在函数 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)