小编mvw*_*vwi的帖子

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

我正在尝试清理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)

python apply dataframe

19
推荐指数
1
解决办法
1万
查看次数

标签 统计

apply ×1

dataframe ×1

python ×1