1

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
  • Can you give some sample input and output? Commented Feb 23, 2017 at 9:39

1 Answer 1

3

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]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.