Numpy: passing ndarray from booleans

I have a situation where I have an ndarray X float, say 100x10, and I want to look at some conditions in the first column and create a logical ndarray B of form 100x1. Then I want to use B as an index in X to get the values ​​where True is located. However, for every True in B, I want to pull out the entire line of X. I thought this would work automatically, since B would be broadcast to form 100x10. However, this does not seem to be the case. Here is an example of using 2x2 and 2x1 ndarrays.

a = np.array([True, False])
a.shape = (2,1)
b = np.array([1, 2, 3, 4])
b.shape = (2,2)
print(a)
print(b)
print(b[a])

Will print

[[True]
 [False]]

[[ 1 2 ]
 [ 3 4 ]]

 [1]

I expected him to print [1 2]. Why does the broadcast work the way I expect?

+4
source share
1 answer

" " . , obj NumPy dtype bool, x[obj]

... ( ) x [obj.nonzero()] , , obj.nonzero() ( obj.ndim) , obj.

In [4]: a.nonzero()
Out[4]: (array([0]), array([0]))

b[a] b[a.nonzero()],

In [6]: b[(np.array([0]), np.array([0]))]
Out[6]: array([1])
In [7]: b[a]
Out[7]: array([1])

a b, , Joran Beasley, a :

import numpy as np

a = np.array([True, False])
b = np.array([1, 2, 3, 4])
b.shape = (2,2)
print(b[a])    
# [[1 2]]
+5

All Articles