相关疑难解决方法(0)

python pandas:将一个带参数的函数应用于一个系列

我想在python pandas中为一个系列应用带参数的函数:

x = my_series.apply(my_function, more_arguments_1)
y = my_series.apply(my_function, more_arguments_2)
...
Run Code Online (Sandbox Code Playgroud)

文档描述了对apply方法的支持,但它不接受任何参数.是否有接受参数的不同方法?或者,我错过了一个简单的解决方法吗?

更新(2017年10月): 请注意,由于此问题最初被要求apply()已更新pandas 以处理位置和关键字参数,上面的文档链接现在反映了这一点并显示了如何包含任一类型的参数.

python apply pandas

114
推荐指数
4
解决办法
14万
查看次数

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

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

python apply dataframe

19
推荐指数
1
解决办法
1万
查看次数

如何将多个参数传递给apply函数

我有一个名为count的方法,它有两个参数.我需要使用apply()方法调用此方法.但是,当我将两个参数传递给apply方法时,它会给出以下错误:

TypeError:counting()只需2个参数(给定1个)

我已经看到了以下线程python pandas:将一个带有参数的函数应用于一个系列.更新,我不想使用functool.partial,因为我不想导入其他类,以便能够传递参数.

def counting(dic, strWord):
    if strWord in dic:
        return dic[strWord]
    else:
        return 0

DF['new_column'] = DF['dic_column'].apply(counting, 'word')
Run Code Online (Sandbox Code Playgroud)

如果我给出一个参数,它可以工作:

def awesome_count(dic):
    if strWord in dic:
       return dic[strWord]
    else:
       return 0

DF['new_column'] = DF['dic_column'].apply(counting)
Run Code Online (Sandbox Code Playgroud)

python python-3.x pandas

10
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×3

apply ×2

pandas ×2

dataframe ×1

python-3.x ×1