Numpy equivalent of if/else without loop

One IF-ELIF

Approach #1 One approach –

keep_mask = x==50
out = np.where(x>50,0,1)
out[keep_mask] = 50

Approach #2 Alternatively, for in-situ edit –

replace_mask = x!=50
x[replace_mask] = np.where(x>50,0,1)[replace_mask]
# Or (x<=50).astype(int) in place of np.where(x>50,0,1)

Code-golf? If you actually want to play code-golf/one-liner –

(x<=50)+(x==50)*49

Multiple IF-ELIFs

Approach #1

For a bit more generic case involving more if-elif parts, we could make use of np.searchsorted

out_x = np.where(x<=40,0, np.searchsorted([40,50,60,70,80,90], x)+3)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)