pandas 将具有多个参数的函数传递给 DataFrame.apply

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49237663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:18:52  来源:igfitidea点击:

Passing a function with multiple arguments to DataFrame.apply

pythonfunctionpandasmultiple-arguments

提问by Michael Henry

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

I know how to use a single argument function with Apply when it comes to dataframes, like this:

当涉及到数据帧时,我知道如何将单参数函数与 Apply 一起使用,如下所示:

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

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.

我不是在寻找解决这个特定示例的变通方法,而是在一般情况下如何做这样的事情。任何建议将不胜感激,谢谢。

采纳答案by cs95

It's just the way you think it would be, applyaccepts argsand kwargsand passes them directly to some_func.

这是现在的样子,你认为这将是,apply接受argskwargs直接传递它们some_func

df.apply(some_func, var1='DOG', axis=1)

Or,

或者,

df.apply(some_func, args=('DOG', ), axis=1)

0    foo-x-DOG
1    bar-y-DOG
dtype: object

回答by jpp

You should use vectorized logic:

您应该使用矢量化逻辑:

df['C'] = df['A'] + '-' + df['B'] + '-DOG'

If you really want to use df.apply, which is just a thinly veiled loop, you can simply feed your arguments as additional parameters:

如果您真的想使用df.apply,这只是一个隐蔽的循环,您可以简单地将您的参数作为附加参数提供:

def some_func(row, var1):
    return '{0}-{1}-{2}'.format(row['A'], row['B'], var1)

df['C'] = df.apply(some_func, var1='DOG', axis=1)

As per the docs, df.applyaccepts both positional and keyword arguments.

根据docsdf.apply接受位置参数和关键字参数。

回答by YOBEN_S

I think it can be

我认为可以

df.apply('-'.join,1)+'-DOG'
Out[157]: 
0    foo-x-DOG
1    bar-y-DOG
dtype: object