Today we’ll be talking about indexing numpy arrays. I’m sure you know how to index regular Python sequences like strings, lists or tuples, just to mention a few. Just a quick reminder: you put the index you need inside a pair of square brackets. This is how you can retrieve an element from a sequence, as well as assign a new value to it.
Indexing 1-Dimensional numpy Arrays
Indexing a 1-dimensional array is pretty straightforward. It works just like with regular Python sequences. We also use square brackets. Let’s compare.
Here’s how you index a regular Python list:
>>> lst = [10, 20, 30, 40, 50]
>>> lst[0], lst[1], lst[-1]
(10, 20, 50)
By the way, if you’re wondering how negative indices work, they are just the indices from the end of a sequence to the beginning, so the last item is at index -1, the second item from the end is at index -2, and so on. This means each element of a sequence may be indexed in two equivalent ways: either with a positive index or with a negatice index. It depends on which one is more comfortable to use in any particular case.
And here’s how you index a numpy array:
>>> arr = np.array(lst)
>>> print(arr)
[10 20 30 40 50]
>>> arr[0], arr[1], arr[-1]
(10, 20, 50)
Multidimensional Arrays
With multidimensional arrays we can use the same syntax as with nested lists.
Here’s how you index a nested Python list:
>>> lst = [[11, 22, 33, 44], [18, 28, 38, 48]]
>>> lst[1][2]
38
So, we use the first index to retrieve the second sublist in the outer list, and then we use the second index to retrieve the third element in that sublist.
And here’s how you index a multidimensional numpy array:
>>> arr = np.array(lst)
>>> print(arr)
[[11 22 33 44]
[18 28 38 48]]
>>> arr[1][2]
38
This works, but it’s inefficient because it creates a temporary intermediate array (arr[1] in this case) which is then indexed with the second index (2 in our case).
This is why it’s recommended to use a different way of indexing multidimensional arrays. We put all the indices in one pair of square brackets:
>>> arr[1, 2]
38
You can index your array to assign new values to its elements as well:
>>> arr[1, 2] = 50
>>> print(arr)
[[11 22 33 44]
[18 28 50 48]]
Here’s the video version: