[Numpy-discussion] Fancy indexing with masks
Stéfan van der Walt
Tue Sep 20 01:43:56 CDT 2011
Matthew Brett showed me an interesting code snippet this evening:
# Construct input data
In : x
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
# Fancy indexing with 1D boolean array
In : x[np.array([True, False, True])]
array([[0, 1, 2],
[6, 7, 8]])
# Fancy indexing with 2D boolean array
In : x[np.array([[True, False, True]])]
Out: 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!
More information about the NumPy-Discussion