# Indexing: A few handy ways to access NumPy arrays

The following code snippets should serve as an (incomplete) cheat sheet for accessing NumPy arrays. All examples expect an `import numpy as np`

.

**Basic access**

NumPy arrays can be accessed just like lists with `array[start:stop:step]`

When working with multidimensional arrays, a comma can be used to access values for the different axes:

Negative values can be used to access the end of the array

**Access using integer index arrays**

To get a subset of an array via the indices, integer arrays can be used. Say we want to access the first, third and fifth element of a one-dimensional array:

This also works for multi-dimensional arrays when one-dimensional arrays are passed for each axis.

In the previous example the two selector (index) arrays are used to access…

- index 0 for axis 0, index 1 for axis 1 (==2)
- index 1 for axis 0, index 2 for axis 1 (==6)
- index 0 for axis 0, index 1 for axis 1 (==2)

To better mentally visualize this, the 2D array axis 0 could be thought of as the “rows”, axis 1 the “columns”.

Selecting across dimensions is also possible. By using the `take`

function, an axis can be specified.

**Access using boolean arrays**

To select using a boolean array, we can do the following:

The same works for boolean expressions like a `logical_or`

, `logical_and`

, `logical_not`

, `logical_xor`

:

Or, as another example, for getting elements which are not (~) NaN:

**More information**

There are, of course, many more ways to juggle around with NumPy arrays. A more complete introduction on indexing can be found at: https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

## Leave a Comment