传递多个参数以应用(Python) [英] Passing multiple arguments to apply (Python)

查看:129
本文介绍了传递多个参数以应用(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在清理Python中的一些代码来向量化一组功能,我想知道是否有一个很好的方法来使用apply来传递多个参数。考虑以下(当前版本):

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)

使用上面我不得不编写一个新的函数(function_1,function_2等)来测试每个子串string我想查找。在一个理想的世界中,我可以组合所有这些冗余的函数,并使用这样的东西:

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"))

但尝试返回错误 TypeError :function()只需要2个参数(1个给定)有另一种方法来完成同样的事情吗?

But trying that returns the error TypeError: function() takes exactly 2 arguments (1 given) Is there another way to accomplish the same thing?

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

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


推荐答案

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

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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆