User guide
NumPy User Guide, Release 1.9.0
>>> y[b[:,5]]
array([[21, 22, 23, 24, 25, 26, 27],
[28, 29, 30, 31, 32, 33, 34]])
Here the 4th and 5th rows are selected from the indexed array and combined to make a 2-D array.
In general, when the boolean array has fewer dimensions than the array being indexed, this is equivalent to y[b, ...],
which means y is indexed by b followed by as many : as are needed to fill out the rank of y. Thus the shape of the result
is one dimension containing the number of True elements of the boolean array, followed by the remaining dimensions
of the array being indexed.
For example, using a 2-D boolean array of shape (2,3) with four True elements to select rows from a 3-D array of
shape (2,3,5) results in a 2-D result of shape (4,5):
>>> x = np.arange(30).reshape(2,3,5)
>>> x
array([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]],
[[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]]])
>>> b = np.array([[True, True, False], [False, True, True]])
>>> x[b]
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]])
For further details, consult the numpy reference documentation on array indexing.
2.4.7 Combining index arrays with slices
Index arrays may be combined with slices. For example:
>>> y[np.array([0,2,4]),1:3]
array([[ 1, 2],
[15, 16],
[29, 30]])
In effect, the slice is converted to an index array np.array([[1,2]]) (shape (1,2)) that is broadcast with the index array
to produce a resultant array of shape (3,2).
Likewise, slicing can be combined with broadcasted boolean indices:
>>> y[b[:,5],1:3]
array([[22, 23],
[29, 30]])
2.4.8 Structural indexing tools
To facilitate easy matching of array shapes with expressions and in assignments, the np.newaxis object can be used
within array indices to add new dimensions with a size of 1. For example:
>>> y.shape
(5, 7)
24 Chapter 2. Numpy basics