If we have two series s1 and s2 we can apply arithmetic operations to them: s1 + s2 or s1*s2. The arithmetic operation will be applied pairwise (assuming that the two series have the same length) as a result we get a new series. This feature makes a lot of things much more easier.

Now, I try to define my own operator and apply it to two series:

def f(x1, x2):
   if x2 > 0:
      return x1/x2
   else:
      return 1000.0

And I try to apply it to two series: f(s1,s2). It does not work. It is expectable, to a certain extent, since the user-defined function doers not know how to treat series. So, my question is if there is an elegant way to do what I want to do?

有帮助吗?

解决方案

In [12]: s1 = pd.Series(np.random.randint(-10, 10, 5))

In [13]: s2 = pd.Series(np.random.randint(-10, 10, 5))

In [14]: s1.combine(s2, f)
Out[14]:
0    1000
1    1000
2      -2
3    1000
4    1000
Dtype: int64
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top