Reputation: 3842
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?
Upvotes: 2
Views: 47
Reputation: 107287
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.
Upvotes: 1