2

Here is my question.

  • a is a 2-d numpy array in the shape of 100x100 containing finite numbers

  • b is a 2-d bool array in the shape of 100x100 containing True and False

My target:

Select specific part of array a when the value of b[i,j] == True

My code here:

 select = a[np.array(np.where(b == True)).T]  

But the result shows like some index are out of boundaries.

Does someone has any idea to achieve that?

2
  • won't a[b] just work here? Commented Jun 9, 2016 at 9:35
  • What shape do you want the output to be? a[b] is the same as a.flatten()[b.flatten()]. It will return a vector with length equal to the number of true values in b. Commented Jun 9, 2016 at 9:39

1 Answer 1

1

That's because you are transposing the index array. Also you don't need to convert the result of np.where() to numpy array, just pass it as index to first array.

Here is an example:

>>> b = np.random.choice([0, 1], size=(10,10))
>>> b
array([[0, 0, 0, 1, 0, 1, 1, 0, 0, 0],
       [0, 1, 1, 0, 0, 0, 0, 1, 1, 1],
       [1, 1, 1, 1, 1, 0, 0, 0, 1, 0],
       [1, 1, 0, 1, 0, 0, 1, 0, 0, 1],
       [0, 1, 0, 0, 1, 1, 1, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 0, 1, 0, 0],
       [0, 1, 1, 1, 0, 0, 0, 0, 0, 0],
       [0, 1, 0, 0, 1, 1, 1, 0, 0, 1],
       [1, 0, 1, 0, 0, 1, 0, 1, 0, 0],
       [1, 0, 0, 1, 0, 1, 1, 0, 0, 1]])
>>> a = np.random.choice(100, size=(10,10))
>>> 
>>> a
array([[47, 90, 94, 11, 17, 65, 95, 57, 36, 43],
       [65, 82, 37, 93, 65, 32,  8, 47, 16, 12],
       [66, 60, 40, 90, 34, 30, 40,  2, 36, 65],
       [ 8, 53, 69,  0, 61, 60, 94, 37, 77, 43],
       [59, 47, 21, 93, 58,  0, 92, 26, 17, 44],
       [98, 16, 33, 56, 39, 30, 14, 93, 93, 58],
       [96, 40, 35, 17, 21, 70, 26,  0, 21, 81],
       [47,  4, 20, 82, 19, 89, 50, 26, 38,  4],
       [60,  3, 72, 56, 78, 55, 60, 53,  3, 87],
       [80,  1, 65,  2, 92, 92, 97, 17, 55, 67]])

>>> a[np.where(b)]
array([11, 65, 95, 82, 37, 47, 16, 12, 66, 60, 40, 90, 34, 36,  8, 53,  0,
       94, 43, 47, 58,  0, 92, 26, 17, 44, 98, 16, 33, 56, 39, 30, 93, 40,
       35, 17,  4, 19, 89, 50,  4, 60, 72, 55, 53, 80,  2, 92, 97, 67])

Note that you are not have to use b==True as np.where condition, when you pass the boolean array it will choose the valid items which are determined by python's Truth Value Testing.

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.