gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:55:20 26 4
gpt4 key购买 nike

我正在尝试清理 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() 只需要 2 个参数(1 个给定) 是否有另一种方法来完成同样的事情?

编辑:

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

df['newFeature'] = df['oldFeature'].apply(partial(function, 'string'))

最佳答案

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

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

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

df['existingFeature'].apply(partial(function, "string"))

关于python - 传递多个参数以应用(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19140035/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com