Beginner in Python here, I have a hard time wrapping my head around vectorizing my 'for' loops. I have a 2D numpy array, containing only two values -1 and 1. For each column and row I want to do the following operation: set all -1 values encountered before the first time a 1 is encountered to 0. Can this be vectorized? Even without crashing if there's no 1 in a row/column and thus the whole row/column is to be set to 0?
1 Answer
Here's one vectorized approach -
mask = a==1
a[~np.maximum.accumulate(mask,axis=0)] = 0
a[~np.maximum.accumulate(mask,axis=1)] = 0
Sample run -
In [39]: a
Out[39]:
array([[ 1, -1, 1, -1, -1],
[ 1, 1, -1, 1, -1],
[-1, 1, -1, 1, -1],
[ 1, -1, -1, -1, -1]])
In [40]: mask = a==1
In [41]: a[~np.maximum.accumulate(mask,axis=0)] = 0
In [42]: a[~np.maximum.accumulate(mask,axis=1)] = 0
In [43]: a
Out[43]:
array([[ 1, 0, 1, 0, 0],
[ 1, 1, -1, 1, 0],
[ 0, 1, -1, 1, 0],
[ 1, -1, -1, -1, 0]])