简体   繁体   English

将函数应用于一对熊猫系列

[英]applying a function to a pair of pandas series

Suppose I have two series:假设我有两个系列:

s = pd.Series([20, 21, 12]
t = pd.Series([17,19 , 11]

I want to apply a two argument function to the two series to get a series of results (as a series).我想将两个参数函数应用于两个系列以获得一系列结果(作为一个系列)。 Now, one way to do it is as follows:现在,一种方法如下:

df = pd.concat([s, t], axis=1)
result = df.apply(lambda x: foo(x[s], x[t]), axis=1)

But this seems clunky.但这似乎很笨拙。 Is there any more elegant way?有没有更优雅的方式?

There are many ways to do what you want.有很多方法可以做你想做的事。

Depending on the function in question, you may be able to apply it directly to the series.根据所讨论的功能,您可以将其直接应用于系列。 For example, calling s + t returns例如,调用s + t返回

0    37
1    40
2    23
dtype: int64

However, if your function is more complicated than simple arithmetic, you may need to get creative.但是,如果您的函数比简单的算术更复杂,您可能需要发挥创造力。 One option is to use the built-in Python map function.一种选择是使用内置的 Python map功能。 For example, calling例如,调用

list(map(np.add, s, t))

returns返回

[37, 40, 23]

If the two series have the same index, you can create a series with list comprehension:如果两个系列具有相同的索引,您可以创建一个具有列表理解的系列:

result = pd.Series([foo(xs, xt) for xs,xt in zip(s,t)], index=s.index)

If you can't guarantee that the two series have the same index, concat is the way to go as it helps align the index.如果您不能保证这两个系列具有相同的索引,则 concat 是一种方法,因为它有助于对齐索引。

如果我理解您可以使用它来应用使用 2 列的函数并将结果复制到另一列中:

df['result'] = df.loc[:, ['s', 't']].apply(foo, axis=1)

It might be possible to use numpy.vectorize :可能可以使用numpy.vectorize

from numpy import vectorize

vect_foo = vectorize(foo)
result = vect_foo(s, t)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM