python pandas:将带参数的函数应用于系列。更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21188504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:34:49  来源:igfitidea点击:

python pandas: apply a function with arguments to a series. Update

pythonpandasapply

提问by user2988577

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

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

python pandas: apply a function with arguments to a series

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

and

Passing multiple arguments to apply (Python)

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

both of them rely on the use of functool.partialand 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:

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

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

It exits with a:

它以以下方式退出:

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

回答by TomAugspurger

The TypeErroris saying that you passed the wrong type to the lambdafunction x + y. It's expecting the argsto 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:

TypeError是说,你传递了错误的类型的lambda功能x + y。它期望args是一个序列,但它有一个int. 你可能认为这(100)是一个元组(一个序列),但在 python 中,逗号构成了一个元组:

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