python pandas:将带参数的函数应用于一系列 [英] python pandas: apply a function with arguments to a series

查看:25
本文介绍了python pandas:将带参数的函数应用于一系列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

x = my_series.apply(my_function, more_arguments_1)y = my_series.apply(my_function, more_arguments_2)...

文档描述了对apply 方法,但它不接受任何参数.是否有不同的方法可以接受参数?或者,我是否缺少一个简单的解决方法?

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

解决方案

较新版本的 pandas do 允许您传递额外的参数(请参阅 新文档).所以现在你可以这样做:

my_series.apply(your_function, args=(2,3,4), extra_kw=1)

位置参数添加在系列元素之后.

<小时>

对于旧版本的熊猫:

文档清楚地解释了这一点.apply 方法接受一个应该有一个参数的 python 函数.如果你想传递更多的参数,你应该使用 functools.partial 正如 Joel Cornett 在他的评论中所建议的那样.

示例:

<预><代码>>>>导入功能工具>>>进口经营者>>>add_3 = functools.partial(operator.add,3)>>>添加_3(2)5>>>添加_3(7)10

您还可以使用 partial 传递关键字参数.

另一种方法是创建一个 lambda:

my_series.apply((lambda x: your_func(a,b,c,d,...,x)))

但我认为使用 partial 更好.

I want to apply a function with arguments to a series in python pandas:

x = my_series.apply(my_function, more_arguments_1)
y = my_series.apply(my_function, more_arguments_2)
...

The documentation describes support for an apply method, but it doesn't accept any arguments. Is there a different method that accepts arguments? Alternatively, am I missing a simple workaround?

Update (October 2017): Note that since this question was originally asked that pandas apply() has been updated to handle positional and keyword arguments and the documentation link above now reflects that and shows how to include either type of argument.

解决方案

Newer versions of pandas do allow you to pass extra arguments (see the new documentation). So now you can do:

my_series.apply(your_function, args=(2,3,4), extra_kw=1)

The positional arguments are added after the element of the series.


For older version of pandas:

The documentation explains this clearly. The apply method accepts a python function which should have a single parameter. If you want to pass more parameters you should use functools.partial as suggested by Joel Cornett in his comment.

An example:

>>> import functools
>>> import operator
>>> add_3 = functools.partial(operator.add,3)
>>> add_3(2)
5
>>> add_3(7)
10

You can also pass keyword arguments using partial.

Another way would be to create a lambda:

my_series.apply((lambda x: your_func(a,b,c,d,...,x)))

But I think using partial is better.

这篇关于python pandas:将带参数的函数应用于一系列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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