Sub topic 2
Selecting Single Elements with Integer Indices
Prerequisites and scope
This chapter assumes you can create arrays with np.array, np.arange, and reshape. It also assumes you know what shape and dtype mean, and that you can index a plain Python list. The previous chapter covered shape and axes. Here we use them to answer one question: which element does an integer index point to, and what comes back?
Slices (start:stop:step), boolean masks, and index arrays are left for later chapters. This chapter only uses integers.
One-dimensional arrays
In a one-dimensional array, an integer index counts from zero, as with a list. A negative index counts from the end, so -1 is the last element.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[0]) # 10
print(a[4]) # 50
print(a[-1]) # 50
print(a[-5]) # 10, the same element as a[0]For an axis of length n, the valid indices run from -n to n - 1. Anything outside that range raises an IndexError. NumPy does not wrap around or clip the index.
import numpy as np
a = np.array([10, 20, 30, 40, 50])
try:
a[5]
except IndexError as e:
print(e) # index 5 is out of bounds for axis 0 with size 5A negative index -k is converted to n - k before the bounds check. That conversion explains why a[-5] works here and a[-6] does not.
Two dimensions: one index per axis
Take a 3 by 4 array. It has two axes: axis 0 runs down the rows and axis 1 runs across the columns.
import numpy as np
a = np.arange(12).reshape(3, 4)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a[1, 2]) # 6, row 1, column 2
print(a[2, 0]) # 8
print(a[-1, -1]) # 11, last row, last column
print(a[0, -2]) # 2, first row, second-to-last columnThe expression a[1, 2] is a single index operation. The comma-separated values form a tuple, (1, 2), and NumPy reads one entry per axis, in axis order. You can build the tuple yourself, which is useful when a function returns a position:
import numpy as np
grid = np.array([[3, 9, 2],
[7, 1, 8]])
flat_position = np.argmax(grid) # 1, an index into the flattened array
idx = np.unravel_index(flat_position, grid.shape) # the (row, column) position, here (0, 1)
print(grid[idx]) # 9np.argmax without an axis argument returns a position in the flattened array. np.unravel_index turns that position into one index per axis. Because the result is a tuple, grid[idx] works exactly like grid[0, 1].
How the index maps to memory
NumPy stores a C-ordered 2-D array row by row. For a 3 by 4 array, the element a[i, j] sits at flat position i * 4 + j. You rarely compute this yourself, but you can check it:
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a.ravel()[1 * 4 + 2]) # 6
print(np.ravel_multi_index((1, 2), (3, 4))) # 6
r, c = np.unravel_index(6, a.shape)
print(r, c) # 1 2This mapping is why indexing is fast. NumPy multiplies each index by that axis's stride, adds the results, and reads one memory location. It does not walk through the rows.
Three dimensions and beyond
The rule is the same for any number of dimensions: one integer per axis, in axis order.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
print(b[1, 2, 3]) # 23, the last element
print(b[0, 0, 0]) # 0
print(b[1, 0, 2]) # 14
print(b[-1, -1, -1]) # 23Read b.shape == (2, 3, 4) as "2 blocks, each with 3 rows, each with 4 columns". Then b[1, 0, 2] means block 1, row 0, column 2. Its flat position is 1*12 + 0*4 + 2 = 14, and since b was built with arange, the value equals that position.
Giving fewer indices than dimensions
If you supply fewer integers than the array has axes, NumPy fills in the remaining axes with full slices. You get a smaller array, not a single element.
import numpy as np
b = np.arange(24).reshape(2, 3, 4)
print(b[1].shape) # (3, 4), a whole block
print(b[1, 2]) # [20 21 22 23]
print(b[1, 2].shape) # (4,)When you use only integers, each one removes one axis. The result has ndim - k dimensions, where k is the number of integers.
| Array shape | Index | Integers used | Result shape |
|---|---|---|---|
| `(5,)` | `a[2]` | 1 | `()`, a scalar |
| `(3, 4)` | `a[1]` | 1 | `(4,)` |
| `(3, 4)` | `a[1, 2]` | 2 | `()`, a scalar |
| `(2, 3, 4)` | `a[1]` | 1 | `(3, 4)` |
| `(2, 3, 4)` | `a[1, 2]` | 2 | `(4,)` |
| `(2, 3, 4)` | `a[1, 2, 3]` | 3 | `()`, a scalar |
`a[i][j]` versus `a[i, j]`
Both forms return the same value when you read, but they work differently.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a[1][2]) # 6
print(a[1, 2]) # 6a[1][2] first builds the intermediate array a[1], then indexes it. a[1, 2] does a single lookup. The chained form is slower and creates a temporary object. It also stops working as soon as the first index is anything other than a plain integer or slice, because that first step may return a copy. Later chapters cover this. Prefer a[i, j] as a habit.
A plain list of lists only supports the chained form. nested[1, 2] on a Python list raises TypeError. This is a common slip for people moving between the two.
What comes back: NumPy scalars
An index that selects one element returns a NumPy scalar, not a Python int or float.
import numpy as np
a = np.arange(12).reshape(3, 4)
x = a[1, 2]
print(type(x)) # <class 'numpy.int64'>
print(x) # 6
print(type(x.item())) # <class 'int'>The exact integer type depends on your platform and NumPy version. On most 64-bit Linux and macOS systems it is numpy.int64. The array's dtype decides the scalar type: a float32 array gives numpy.float32 scalars, and so on.
NumPy scalars behave like numbers in arithmetic. Call .item() when you need a true Python object, for example before serializing to JSON, which does not accept NumPy scalar types.
Assigning to a single element
Put the index on the left of = to overwrite one element.
import numpy as np
a = np.arange(12).reshape(3, 4)
a[0, 0] = 99
a[-1, -1] = -1
print(a)
# [[99 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 -1]]The array keeps its dtype, so the assigned value is converted to fit. For an integer array, a float is truncated toward zero without any warning.
import numpy as np
a = np.arange(5) # integer dtype
a[0] = 7.9
a[1] = -2.9
print(a) # [ 7 -2 2 3 4]This is a quiet source of bugs. If you expected 7.9 to be stored, create the array with a float dtype instead, for example np.arange(5, dtype=float). Values that cannot be converted at all, such as np.nan into an integer array, raise ValueError.
Reading a row also gives you a live window
With fewer indices than dimensions, the result is a view onto the original data, not a copy. Writing into it changes the original array.
import numpy as np
a = np.arange(12).reshape(3, 4)
row = a[1]
row[0] = 100
print(a[1, 0]) # 100That is why a[1][2] = 5 works as an assignment: a[1] is a view, so the write lands in a. A later chapter covers when views are guaranteed and when they are not. For now, remember that a single element is copied out, while a lower-dimensional piece is shared.
Common errors
Three errors come up repeatedly with integer indexing.
import numpy as np
a = np.arange(12).reshape(3, 4)
for index in [(3, 0), (0, 1, 2), 1.0]:
try:
a[index]
except IndexError as e:
print(type(e).__name__, "-", e)Run on a current NumPy, this prints three lines, one for each failure:
(3, 0)raisesIndexErrorsaying index 3 is out of bounds for axis 0 with size 3. The row index is past the last row.(0, 1, 2)raisesIndexErrorsaying there are too many indices for the array: the array is 2-dimensional, but 3 were indexed.1.0raisesIndexErrorsaying that only integers, slices, ellipsis,numpy.newaxis, and integer or boolean arrays are valid indices. A float is not an integer index, even when its value is whole.
When you see the first error, check the axis number in the message. It tells you which of your indices is wrong, which matters in 3-D and higher. When you see the second, print a.shape and a.ndim and count your indices against them. Fix the third with int(value) or by computing the index with integer arithmetic (// instead of /).
NumPy integer types such as np.int64 are accepted as indices, so the result of np.argmax or np.argmin can be used directly.
Summary
- One integer per axis, in axis order, picks one element. Negative values count from the end of that axis.
- Valid indices on an axis of length
nare-nthroughn - 1. Everything else raisesIndexError. - Using fewer integers than
ndimreturns a view withndim - kdimensions. Using exactlyndimreturns a NumPy scalar. - Use
a[i, j], nota[i][j]. - Assignment converts the value to the array's dtype, which can truncate floats.
Exercise
Given b = np.arange(24).reshape(2, 3, 4), what do b[-1, -1, -1] and b[0, 1] return? State the value of the first and the shape of the second.
Show answer
b[-1, -1, -1] is the last element of the last row of the last block, which is 23. b[0, 1] uses two integers on a 3-D array, so one axis remains. It returns row 1 of block 0, the array [4 5 6 7], with shape (4,).
Exercise
You have a = np.arange(12).reshape(3, 4). Write the expression that returns the last element of the second row using one index operation. Then say why it is preferable to a[1][-1].
Show answer
a[1, -1] returns 7. It does a single lookup, while a[1][-1] first creates the intermediate array a[1] and then indexes it. The chained form is also fragile once the first index becomes something other than an integer or slice.
Exercise
a = np.arange(5) has an integer dtype. After a[2] = 3.9, what is a[2], and how would you keep the 3.9?
Show answer
a[2] is 3, because the float is truncated to fit the integer dtype and no warning is raised. To keep 3.9, create the array with a float dtype, for example np.arange(5, dtype=float), or convert with a = a.astype(float) before assigning.