Home > Mobile >  applying a function to a pair of pandas series
applying a function to a pair of pandas series

Time:06-14

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?

CodePudding user response:

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

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. For example, calling

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

returns

[37, 40, 23]

CodePudding user response:

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.

CodePudding user response:

If I understand you can use this to apply a function using 2 colums and copy the results in another column:

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

CodePudding user response:

It might be possible to use numpy.vectorize:

from numpy import vectorize

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