bet*_*eta 23 python apply dataframe pandas pandas-groupby
我想df.groupby()结合使用apply()将函数应用于每组的每一行.
我通常使用以下代码,这通常有效(请注意,这是没有的groupby()):
df.apply(myFunction, args=(arg1,))
Run Code Online (Sandbox Code Playgroud)
随着groupby()我尝试了以下内容:
df.groupby('columnName').apply(myFunction, args=(arg1,))
Run Code Online (Sandbox Code Playgroud)
但是,我收到以下错误:
TypeError:myFunction()得到一个意外的关键字参数'args'
因此,我的问题是:我如何使用groupby()和apply()需要参数的函数?
Max*_*axU 21
pandas.core.groupby.GroupBy.apply没有命名参数args,但pandas.DataFrame.apply确实有它.
试试这个:
df.groupby('columnName').apply(lambda x: myFunction(x, arg1))
Run Code Online (Sandbox Code Playgroud)
或者根据@Zero的建议:
df.groupby('columnName').apply(myFunction, ('arg1'))
Run Code Online (Sandbox Code Playgroud)
演示:
In [82]: df = pd.DataFrame(np.random.randint(5,size=(5,3)), columns=list('abc'))
In [83]: df
Out[83]:
a b c
0 0 3 1
1 0 3 4
2 3 0 4
3 4 2 3
4 3 4 1
In [84]: def f(ser, n):
...: return ser.max() * n
...:
In [85]: df.apply(f, args=(10,))
Out[85]:
a 40
b 40
c 40
dtype: int64
Run Code Online (Sandbox Code Playgroud)
使用时,GroupBy.apply您可以传递命名参数:
In [86]: df.groupby('a').apply(f, n=10)
Out[86]:
a b c
a
0 0 30 40
3 30 40 40
4 40 20 30
Run Code Online (Sandbox Code Playgroud)
一个参数元组:
In [87]: df.groupby('a').apply(f, (10))
Out[87]:
a b c
a
0 0 30 40
3 30 40 40
4 40 20 30
Run Code Online (Sandbox Code Playgroud)
关于为什么使用args参数抛出错误的一些混淆可能源于pandas.DataFrame.apply具有args参数(元组)的事实,而pandas.core.groupby.GroupBy.apply不是.
因此,当您调用.applyDataFrame本身时,您可以使用此参数; 当你调用.applygroupby对象时,你不能.
在@ MaxU的答案中,表达式lambda x: myFunction(x, arg1)被传递给func(第一个参数); 没有必要指定其他*args/ **kwargs因为arg1在lambda中指定.
一个例子:
import numpy as np
import pandas as pd
# Called on DataFrame - `args` is a 1-tuple
# `0` / `1` are just the axis arguments to np.sum
df.apply(np.sum, axis=0) # equiv to df.sum(0)
df.apply(np.sum, axis=1) # equiv to df.sum(1)
# Called on groupby object of the DataFrame - will throw TypeError
print(df.groupby('col1').apply(np.sum, args=(0,)))
# TypeError: sum() got an unexpected keyword argument 'args'
Run Code Online (Sandbox Code Playgroud)