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