0

I have two arrays A and B of the same size. I'd need to get the values and indices of items in the arrays according to B's items. Here is my code:

promotes = [a for a,b in zip(A, B) if b == 1]
demotes =  [a for a,b in zip(A, B) if b == 0]
promotes_index = [k for k,(a,b) in enumerate(zip(A, B)) if b == 1]
demotes_index =  [k for k,(a,b) in enumerate(zip(A, B)) if b == 0] 

I'm sure there is a more efficient way to compute promotes, demotes, and the indices.

In more simple words, if A and promotes are like:

A = array([ 4,  6,  9, 10]))
promotes = array([4, 9])

how could I get promote_index from A and promotes:

promotes_index = array([0, 2])

I appreciate any response.

1
  • Are A and B np arrays or lists? Commented Nov 10, 2016 at 23:08

1 Answer 1

2

We could use array programming there to do things in a vectorized manner. We start off by creating boolean arrays corresponding to the conditionals. Then, we use those masks to index into A with boolean-indexing to get promotes and demotes -

mask1, mask2 = B==1, B==0
promotes, demotes = A[mask1], A[mask2]

Finally, we use np.flatnonzero on those masks to get the corresponding indices -

promotes_index, demotes_index = np.flatnonzero(mask1), np.flatnonzero(mask2)

Please note that if B consists of 1s and 0s only, mask2 would be simply ~mask1.

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.