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
Like to comment? Feel free to send me an email or reach out on Twitter.
Did this or another article help you? If you like and can afford it, you can buy me a coffee (3 EUR) ☕️ to support me in writing more posts. In case you would like to contribute more or I helped you directly via email or coding/troubleshooting session, you can opt to give a higher amount through the following links or adjust the quantity: 50 EUR, 100 EUR, 500 EUR. All links redirect to Stripe.