传递多个参数以应用(Python)

mvw*_*vwi 19 python apply dataframe

我正在尝试清理Python中的一些代码来矢量化一组功能,我想知道是否有一种使用apply来传递多个参数的好方法.考虑以下(当前版本):

def function_1(x):
    if "string" in x:
        return 1
    else:
        return 0

df['newFeature'] = df['oldFeature'].apply(function_1)
Run Code Online (Sandbox Code Playgroud)

有了上面的内容,我不得不编写一个新函数(function_1,function_2等)来测试"string"我想要查找的每个子字符串.在理想的世界中,我可以将所有这些冗余函数组合在一起,并使用以下内容:

def function(x, string):
    if string in x:
        return 1
    else:
        return 0

df['newFeature'] = df['existingFeature'].apply(function("string"))
Run Code Online (Sandbox Code Playgroud)

但尝试返回错误TypeError: function() takes exactly 2 arguments (1 given)是否有另一种方法来完成同样的事情?

编辑:

def function(string, x):
    if string in x:
        return 1
    else:
        return 0

df['newFeature'] = df['oldFeature'].apply(partial(function, 'string'))
Run Code Online (Sandbox Code Playgroud)

Rom*_*huk 14

我相信你想要的functools.partial.演示:

>>> from functools import partial
>>> def mult(a, b):
...     return a * b
...
>>> doubler = partial(mult, 2)
>>> doubler(4)
8
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你需要交换参数function(因为的想法partial),然后只是

df['existingFeature'].apply(partial(function, "string"))
Run Code Online (Sandbox Code Playgroud)