使用Groupby时调用具有多个参数的函数

2024-06-26 13:47:35 发布

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

编写要与一起使用的函数时groupby.apply或者groupby.transform在pandaps中,如果函数有多个参数,那么当作为groupby的一部分调用函数时,参数跟在逗号后面而不是括号中。例如:

def Transfunc(df, arg1, arg2, arg2):
     return something

GroupedData.transform(Transfunc, arg1, arg2, arg3)

其中df参数作为第一个参数自动传递。在

但是,在使用函数对数据进行分组时,似乎不可能使用相同的语法。以下面的例子为例:

^{pr2}$

上面的方法很好,但是我不明白为什么要用lambda来包装函数。根据transform and apply使用的语法,我认为以下方法应该可以正常工作:

people.groupby(MeanPosition, people, 'a').mean()

有人能告诉我为什么吗?或者我如何在不使用lambda包装的情况下调用函数?在

谢谢

编辑:我认为不可能通过传递函数作为键来分组数据,而不将该函数包装在lambda中。一种可能的解决方法是传递由函数创建的数组,而不是将函数作为键传递。这将以以下方式工作:

def MeanPositionList(df, Column):
    return ['Greater Group' if df[Column][row] >= np.mean(df[Column]) else 'Lesser Group' for row in df.index]

Grouped = people.groupby(np.array(MeanPositionList(people, 'a')))
Grouped.mean()

但当然,最好是把中间人函数都去掉,只使用一个带有列表压缩的数组。。。。在


Tags: 方法lambda函数df参数deftransformcolumn
1条回答
网友
1楼 · 发布于 2024-06-26 13:47:35

将参数传递给apply正好可以,因为apply将所有参数传递给目标函数。在

但是,groupby需要多个参数,请参见here,因此无法区分参数;传递lambda/命名函数更显式,而且是正确的方法。在

下面是如何做我认为您想要的(稍微修改一下,因为您的示例中有所有不同的组)

In [22]: def f(x):
   ....:     result = Series('Greater',index=x.index)
   ....:     result[x<x.mean()] = 'Lesser'
   ....:     return result
   ....: 

In [25]: df = DataFrame(np.random.randn(5, 5), columns=['a', 'b', 'c', 'd', 'e'], index=['Joe', 'Joe', 'Wes', 'Wes', 'Travis'])

In [26]: df
Out[26]: 
               a         b         c         d         e
Joe    -0.293926  1.006531  0.289749 -0.186993 -0.009843
Joe    -0.228721 -0.071503  0.293486  1.126972 -0.808444
Wes     0.022887 -1.813960  1.195457  0.216040  0.287745
Wes    -1.520738 -0.303487  0.484829  1.644879  1.253210
Travis -0.061281 -0.517140  0.504645 -1.844633  0.683103

In [27]: df.groupby(df.index.values).transform(f)
Out[27]: 
              a        b        c        d        e
Joe      Lesser  Greater   Lesser   Lesser  Greater
Joe     Greater   Lesser  Greater  Greater   Lesser
Travis  Greater  Greater  Greater  Greater  Greater
Wes     Greater   Lesser  Greater   Lesser   Lesser
Wes      Lesser  Greater   Lesser  Greater  Greater

相关问题 更多 >