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

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

问题描述

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

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

文档描述了对apply方法,但不接受任何参数.是否存在接受参数的其他方法?另外,我是否缺少一个简单的解决方法?

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?

更新(2017年10月):请注意,由于最初询问该问题以来,熊猫apply()已更新为处理位置和关键字参数,并且上面的文档链接现在反映了这一点,并说明了如何包括两种类型的参数.

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.

推荐答案

熊猫的新版本 do 允许您传递其他参数(请参见

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.

对于较早版本的熊猫:

文档对此进行了明确说明. apply方法接受一个python函数,该函数应具有一个参数.如果要传递更多参数,则应使用Joel Cornett在其注释中建议的functools.partial.

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.

一个例子:

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

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

You can also pass keyword arguments using partial.

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

Another way would be to create a lambda:

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

但是我认为使用partial更好.

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

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