将具有多个参数的函数传递给DataFrame.apply [英] Passing a function with multiple arguments to DataFrame.apply
问题描述
假设我有一个像这样的数据框:
Suppose I have a dataframe like this:
df = pd.DataFrame([['foo', 'x'], ['bar', 'y']], columns=['A', 'B'])
A B
0 foo x
1 bar y
对于数据帧,我知道如何在Apply中使用单个参数函数,如下所示:
I know how to use a single argument function with Apply when it comes to dataframes, like this:
def some_func(row):
return '{0}-{1}'.format(row['A'], row['B'])
df['C'] = df.apply(some_func, axis=1)
df
A B C
0 foo x foo-x
1 bar y bar-y
当数据框包含多个输入参数时,如何使用Apply?这是我想要的示例:
How can I use apply on dataframes when they involve multiple input arguments? Here's an example of what I want:
def some_func(row, var1):
return '{0}-{1}-{2}'.format(row['A'], row['B'], var1)
df['C'] = df.apply(some_func(row, var1='DOG'), axis=1)
df
A B C
0 foo x foo-x-DOG
1 bar y bar-y-DOG
我不是在寻找解决此特定示例的方法,而只是在一般情况下如何执行此操作.任何建议将不胜感激,谢谢.
I'm not looking for work-arounds to solve this one particular example, just how to do something like this in general. Any advice would be well appreciated, thanks.
推荐答案
这就是您的想法, apply
接受 args
和 kwargs
并将它们直接传递到 some_func
.
It's just the way you think it would be, apply
accepts args
and kwargs
and passes them directly to some_func
.
df.apply(some_func, var1='DOG', axis=1)
或者,
df.apply(some_func, args=('DOG', ), axis=1)
0 foo-x-DOG
1 bar-y-DOG
dtype: object
这篇关于将具有多个参数的函数传递给DataFrame.apply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!