[Solved] Need help conditionally vectorizing a list [closed]


You can use pandas:

import pandas as pd

l = [-1.5,-1,-1,0,0,-1,0,1.5,1,1,1,1,0,0,0,0,1,0,1,0,1.5,1,1,1,1,0,0,0,0,-1.5]
s  = pd.Series(l)
cond1 = (s == 1.5)
cond2 = (s == -1.5)
cond3 = (s == 0)
cond4 = ((s == 1) | (s ==  -1)) & (s.shift() == 0)
out = pd.Series(pd.np.select([cond1, cond2, cond3, cond4],[1, -1, 0 ,0], pd.np.nan)).ffill()
out.tolist()

Output:

[-1.0,
 -1.0,
 -1.0,
 0.0,
 0.0,
 0.0,
 0.0,
 1.0,
 1.0,
 1.0,
 1.0,
 1.0,
 0.0,
 0.0,
 0.0,
 0.0,
 0.0,
 0.0,
 0.0,
 0.0,
 1.0,
 1.0,
 1.0,
 1.0,
 1.0,
 0.0,
 0.0,
 0.0,
 0.0,
 -1.0]

Note: This is a vectorized way of doing if then else using Numpy method np.select, which is accessed via the pandas import using pd.np.select. The default value will be np.nan which allows the forward fill to get previous rows value in that default case.

1

solved Need help conditionally vectorizing a list [closed]