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

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

问题描述

我想将带参数的函数应用于熊猫系列:我找到了两种不同的 SO 解决方案:

I would like to apply a function with argument to a pandas series: I have found two different solution of SO:

python pandas:应用带有参数的函数系列

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

它们都依赖于 functool.partial 的使用并且它们工作得非常好.顺便说一下,新版本的 Pandas 支持多个参数:无论如何我不明白它是如何工作的.示例:

both of them rely on the use of functool.partial and they works absolutely fine. By the way the new version of Pandas support multiple argument: in any case I do not understand how does it works. Example:

a=pd.DataFrame({'x':[1,2],'y':[10,20]})
a['x'].apply(lambda x,y: x+y, args=(100))

它以一个:

TypeError: <lambda>() argument after * must be a sequence, not int

推荐答案

TypeError 表示您将错误的类型传递给 lambda 函数 x +y.它期望 args 是一个序列,但它得到了一个 int.你可能认为 (100) 是一个元组(一个序列),但在 python 中,逗号是一个元组:

The TypeError is saying that you passed the wrong type to the lambda function x + y. It's expecting the args to be a sequence, but it got an int. You may have thought that (100) was a tuple (a sequence), but in python it's the comma that makes a tuple:

In [10]: type((100))
Out[10]: int

In [11]: type((100,))
Out[11]: tuple

所以把你的最后一行改为

So change your last line to

In [12]: a['x'].apply(lambda x, y: x + y, args=(100,))
Out[12]: 
0    101
1    102
Name: x, dtype: int64

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

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