User guide
NumPy User Guide, Release 1.9.0
array([[ 7, 10, 13],
[21, 24, 27]])
Note that slices of arrays do not copy the internal array data but also produce new views of the original data.
It is possible to index arrays with other arrays for the purposes of selecting lists of values out of arrays into new arrays.
There are two different ways of accomplishing this. One uses one or more arrays of index values. The other involves
giving a boolean array of the proper shape to indicate the values to be selected. Index arrays are a very powerful tool
that allow one to avoid looping over individual elements in arrays and thus greatly improve performance.
It is possible to use special features to effectively increase the number of dimensions in an array through indexing so
the resulting array aquires the shape needed for use in an expression or with a specific function.
2.4.4 Index arrays
Numpy arrays may be indexed with other arrays (or any other sequence- like object that can be converted to an array,
such as lists, with the exception of tuples; see the end of this document for why this is). The use of index arrays
ranges from simple, straightforward cases to complex, hard-to-understand cases. For all cases of index arrays, what is
returned is a copy of the original data, not a view as one gets for slices.
Index arrays must be of integer type. Each value in the array indicates which value in the array to use in place of the
index. To illustrate:
>>> x = np.arange(10,1,-1)
>>> x
array([10, 9, 8, 7, 6, 5, 4, 3, 2])
>>> x[np.array([3, 3, 1, 8])]
array([7, 7, 9, 2])
The index array consisting of the values 3, 3, 1 and 8 correspondingly create an array of length 4 (same as the index
array) where each index is replaced by the value the index array has in the array being indexed.
Negative values are permitted and work as they do with single indices or slices:
>>> x[np.array([3,3,-3,8])]
array([7, 7, 4, 2])
It is an error to have index values out of bounds:
>>> x[np.array([3, 3, 20, 8])]
<type ’exceptions.IndexError’>: index 20 out of bounds 0<=index<9
Generally speaking, what is returned when index arrays are used is an array with the same shape as the index array,
but with the type and values of the array being indexed. As an example, we can use a multidimensional index array
instead:
>>> x[np.array([[1,1],[2,3]])]
array([[9, 9],
[8, 7]])
2.4.5 Indexing Multi-dimensional arrays
Things become more complex when multidimensional arrays are indexed, particularly with multidimensional index
arrays. These tend to be more unusal uses, but theyare permitted, and they are useful for some problems. We’ll start
with thesimplest multidimensional case (using the array y from the previous examples):
22 Chapter 2. Numpy basics