Ricky Parker
Ricky Parker

Reputation: 143

How to compute series with different index?

For example, I have two series

X = pd.Series([0,3,4,0,-1,0])
Y = pd.Series([4,2,5,1,3,5])

And I want to generate a new series Z.

import pandas as pd
Z = []
for index in range(0,len(X)):
    if(X.iloc[index]!=0):
       temp = #(Do some arithmetic)
       Z.append(temp)
    elif(X.iloc[index]==0):
       temp = #(Do some arithmetic)
       Z.append(temp)

Due to the efficiency , is it possible don't need to use For-Loop?

Maybe like :

Z = Y*Y [X != 0]
Z = Y*Y*Y [X == 0]
#I know this is wrong,but I dont know how to correct it

I'm not familar with pandas , please tell me , tks!

Upvotes: 0

Views: 39

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210972

IIUC it doesn't matter whether you add or subtract a zero value:

In [245]: (Y-X)/X.abs()
Out[245]:
0    3.000000
1   -0.333333
2    0.250000
3         inf
4    4.000000
5         NaN
dtype: float64

Upvotes: 2

Related Questions