[Numpy-discussion] Logical indexing and higher-dimensional arrays.

Stéfan van der Walt stefan@sun.ac...
Tue Feb 7 14:15:56 CST 2012

On Tue, Feb 7, 2012 at 10:41 AM, Sturla Molden <sturla@molden.no> wrote:
> It's the combination of a single index and fancy indexing that does
> this, not the slicing.

There are some quirks in the broadcasting machinery that makes it
almost impossible to guess what the outcome of mixed indexing is going
to be.  The safest is to stick either to slicing or to fancy indexing,

In [64]: idx1 = np.arange(x.shape[1])[:, None]

In [65]: idx2 = np.array([False, True, False, True])

In [66]: idx1.shape, idx2.shape
Out[66]: ((3, 1), (4,))

In [67]: np.broadcast_arrays(idx1, idx2)[0].shape
Out[67]: (3, 4)

The output will be (.., 3, 4), except that idx2 only has two True
elements, so (..., 3, 2).

In [68]: x[0, idx1, idx2].shape
Out[68]: (3, 2)


More information about the NumPy-Discussion mailing list