user7468395
user7468395

Reputation: 1349

How to vectorize if statement when several statements are affected?

I want to vectorize my python code.

I am able to replace a simple if statement in an elegant way, if there is just one statement that should be executed afterwards:

if a < b:
    c = 5

gets to:

c = np.where(a<b,5,c)

Is there any elegant way of vectorisation, if there are a lot of statements that follow the if statement?:

if a y b:
    c = 5
    d = 6
    e = 7
    f = 8
    .... 
    z = 99

I would like to avoid having a lot similar (somehow unpythonic) statements like:

c = np.where(a<b,5,c)
d = np.where(a<b,6,c)
e = np.where(a<b,7,c)
f = np.where(a<b,8,c)
.... 
z = np.where(a<b,99,c)

It does not seem possible to use tuples for np.where or am I wrong?

Upvotes: 0

Views: 68

Answers (1)

Ardweaden
Ardweaden

Reputation: 887

Maybe you could do something like this:

ind = c[np.repeat([b>a],c.shape[0],axis=0)]
c[np.repeat([b>a],c.shape[0],axis=0)] = np.repeat(d,int(ind.shape[0]/d.shape[0]))

where c is an array of the shape (number of statements, length of a) (It can be initialised with np.zeros((number of statements, length of a)) for example) and d is the array of values ([5,6,7,8..99]).

Upvotes: 1

Related Questions