传递多个参数来应用(Python) [英] Passing multiple arguments to apply (Python)
问题描述
我正在尝试清理 Python 中的一些代码以向量化一组功能,我想知道是否有使用 apply 传递多个参数的好方法.考虑以下(当前版本):
def function_1(x):如果 x 中的字符串":返回 1别的:返回 0df['newFeature'] = df['oldFeature'].apply(function_1)
根据上述内容,我必须编写一个新函数(function_1、function_2 等)来测试我想要查找的每个子字符串 "string"
.在理想的世界中,我可以组合所有这些冗余功能并使用如下所示的内容:
def 函数(x,字符串):如果 x 中的字符串:返回 1别的:返回 0df['newFeature'] = df['existingFeature'].apply(function("string"))
但是尝试返回错误 TypeError: function() 需要 2 个参数(给定 1 个)
还有另一种方法可以完成同样的事情吗?
def 函数(字符串,x):如果 x 中的字符串:返回 1别的:返回 0df['newFeature'] = df['oldFeature'].apply(partial(function, 'string'))
我相信你想要 <代码>functools.partial.演示:
<预><代码>>>>从 functools 导入部分>>>def mult(a, b):...返回 a * b...>>>倍增器 = 部分(多,2)>>>倍增器(4)8在你的情况下,你需要在 function
中交换参数(因为 partial
的想法),然后只是
df['existingFeature'].apply(partial(function, "string"))
I'm trying to clean up some code in Python to vectorize a set of features and I'm wondering if there's a good way to use apply to pass multiple arguments. Consider the following (current version):
def function_1(x):
if "string" in x:
return 1
else:
return 0
df['newFeature'] = df['oldFeature'].apply(function_1)
With the above I'm having to write a new function (function_1, function_2, etc) to test for each substring "string"
that I want to find. In an ideal world I could combine all of these redundant functions and use something like this:
def function(x, string):
if string in x:
return 1
else:
return 0
df['newFeature'] = df['existingFeature'].apply(function("string"))
But trying that returns the error TypeError: function() takes exactly 2 arguments (1 given)
Is there another way to accomplish the same thing?
Edit:
def function(string, x):
if string in x:
return 1
else:
return 0
df['newFeature'] = df['oldFeature'].apply(partial(function, 'string'))
I believe you want functools.partial
. A demo:
>>> from functools import partial
>>> def mult(a, b):
... return a * b
...
>>> doubler = partial(mult, 2)
>>> doubler(4)
8
In your case you need to swap arguments in function
(because of idea of partial
), and then just
df['existingFeature'].apply(partial(function, "string"))
这篇关于传递多个参数来应用(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!