[Numpy-discussion] How does Boolean indexing work?

Anne Archibald peridot.faceted@gmail....
Tue Jun 3 22:59:28 CDT 2008

```Hi,

I thought it might be useful to summarize the different ways to use
numpy's indexing, slice and fancy. The document so far is here:

http://www.scipy.org/Cookbook/Indexing

While writing it I ran into some puzzling issues. The first of them
is, how is Boolean indexing supposed to work when given more than one
array? What I mean is, suppose we have the following array:

In [3]: A = np.arange(9)

In [4]: B = np.reshape(A,(3,3))

In [5]: B
Out[5]:
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])

Then we can use boolean indexing to select some rows or some columns:

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

In [13]: B[:,np.array([True,False,True])]
Out[13]:
array([[0, 2],
[3, 5],
[6, 8]])

But if you supply Boolean arrays in both row and column places, rather
than select the corresponding rows and columns, you get something
basically mysterious:
In [14]: B[np.array([True,False,True]),np.array([True,True,False])]
Out[14]: array([0, 7])

In [15]: B[np.array([True,False,True]),np.array([True,False,False])]
Out[15]: array([0, 6])

In [16]: B[np.array([True,False,True]),np.array([True,True,True])]
---------------------------------------------------------------------------
<type 'exceptions.ValueError'>            Traceback (most recent call last)

/home/peridot/<ipython console> in <module>()

<type 'exceptions.ValueError'>: shape mismatch: objects cannot be
broadcast to a single shape

What is going on here?

Thanks,
Anne
```