[Numpy-discussion] Fancy indexing with masks
Robert Kern
robert.kern at gmail.com
Tue Sep 20 03:43:52 EDT 2011
2011/9/20 Stéfan van der Walt <stefan at sun.ac.za>:
> 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.
If the array is short in a dimension, it gets implicitly continued
with Falses. You can see this in one dimension:
[~]
|1> x = np.arange(12)
[~]
|2> x[np.array([True, False, True])]
array([0, 2])
I honestly don't know if this is documented or tested anywhere or even
if this existed in older versions.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
-- Umberto Eco
More information about the NumPy-Discussion
mailing list