Pandas GroupBy:应用带有两个参数的函数 [英] Pandas GroupBy: apply a function with two arguments
问题描述
通常在使用 .apply()
方法时,会传递一个只接受一个参数的函数.
Usually when using the .apply()
method, one passes a function that takes exactly one argument.
def somefunction(group):
group['ColumnC'] == group['ColumnC']**2
return group
df.groupby(['ColumnA', 'ColumnB']).apply(somefunction)
这里 somefunction
应用于每个 group
,然后返回.基本上我使用这个这里的例子.
Here somefunction
is applied for each group
, which is then returned. Basically I'm using this example here.
我希望能够不指定列名ColumnC
.将它作为 somefunction
的参数传递会使代码更灵活.
I want to have the ability to not specify the column name ColumnC
beforehand. Passing it along as an argument of somefunction
would make the code more flexible.
def somefunction(group, column_name):
group[column_name] == group[column_name]**2
return group
df.groupby(['ColumnA', 'ColumnB']).apply(somefunction)
有什么办法可以使这个工作?我无法将 group
传递给 somefunction
,因为这是由 .apply()
在后台神奇地完成的.
Is there any way to make this work? I can't pass group
to somefunction
, because that is magically done by .apply()
in the background.
推荐答案
可以通过apply
df.groupby(['ColumnA', 'ColumnB']).apply(somefunction, column_name='col')
<小时>
df = pd.DataFrame(dict(A=list(range(2)) * 5, B=range(10)[::-1]))
def f(df, arg1):
return df * arg1
df.groupby('A').apply(f, arg1=3)
A B
0 0 27
1 3 24
2 0 21
3 3 18
4 0 15
5 3 12
6 0 9
7 3 6
8 0 3
9 3 0
这篇关于Pandas GroupBy:应用带有两个参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!