我试图简化Python中的一些代码来向量化一组功能,我想知道是否有一种很好的方式来使用apply来传递多个参数。考虑以下(当前版本):
def function_1(x):
if "string" in x:
return 1
else:
return 0
df['newFeature'] = df['oldFeature'].apply(function_1)
通过上面的介绍,我不得不编写一个新函数(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"))
但尝试返回错误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'))