[Numpy-discussion] Fancy indexing with masks

Stéfan van der Walt stefan@sun.ac...
Tue Sep 20 01:43:56 CDT 2011


Hi all,

Matthew Brett showed me an interesting code snippet this evening:

# Construct input data

In [15]: x
Out[15]:
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])

# Fancy indexing with 1D boolean array

In [16]: x[np.array([True, False, True])]
Out[16]:
array([[0, 1, 2],
       [6, 7, 8]])

# Fancy indexing with 2D boolean array

In [17]: x[np.array([[True, False, True]])]
Out[18]: array([0, 2])


I guess it's been a long day, but why does this work at all?

I expected the first example to break, because the 1D mask does not
match the number of rows in x.  In the second example, I expected an
error because the 2D mask was not of the same shape as x.  But, oddly,
both work. There's also no attempt at broadcasting indexes.

Any hints would be appreciated!

Thanks
Stéfan


More information about the NumPy-Discussion mailing list