Sub topic 2
Selecting single elements with integer indices
This chapter assumes you know basic Python lists, can create arrays with np.array, np.arange, and reshape, and know what an array's shape and dtype are. An integer index picks exactly one position along an axis. It is the base for slicing, masks, and fancy indexing in later chapters.
One dimension
A one-dimensional array indexes like a Python list. Positions start at 0, and negative numbers count from the end.
import numpy as np
v = np.array([10, 20, 30, 40, 50])
print(v[0]) # 10
print(v[-1]) # 50
print(v[-2]) # 40
v[1] = 25 # assignment writes into the array
print(v) # [10 25 30 40 50]For an array of length n, valid indices run from -n to n - 1. The index -1 is shorthand for n - 1.
Several dimensions
A two-dimensional array has two axes: axis 0 runs down the rows, and axis 1 runs across the columns. You give one integer per axis, separated by commas, in a single pair of brackets.
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[-1, -1]) # 11, last row, last column
print(a[1][2]) # 6, same value, but see the note belowFewer indices than dimensions
If you give fewer integers than the array has axes, NumPy fills in the remaining axes with "everything". The result has fewer dimensions than the original.
import numpy as np
a = np.arange(12).reshape(3, 4)
row = a[1]
print(row) # [4 5 6 7]
print(row.shape) # (4,)
b = np.arange(24).reshape(2, 3, 4)
print(b[1, 2, 3]) # 23
print(b[1].shape) # (3, 4)
print(b[1, 2].shape) # (4,)Each integer index removes one axis. The shape of the result is the original shape with the indexed axes dropped.
What you get back
Indexing with one integer per axis returns a NumPy scalar, not a Python int. Its type depends on the array's dtype.
import numpy as np
a = np.arange(12).reshape(3, 4)
x = a[1, 2]
print(type(x)) # <class 'numpy.int64'> on most platforms
print(x + 1) # 7A NumPy scalar behaves like a number in arithmetic. It also carries the dtype, so overflow follows the array's integer width. Call .item() if you need a plain Python value.
Fewer indices than axes return an array. That array is a view into the original, which matters when you assign through it. Chapter "Views versus copies" covers this in detail.
import numpy as np
a = np.arange(12).reshape(3, 4)
a[1, 2] = 60 # set one element
a[0] = 0 # set an entire row; 0 is broadcast across it
print(a)
# [[ 0 0 0 0]
# [ 4 5 60 7]
# [ 8 9 10 11]]Errors you will see
Unlike slices, integer indices are never clipped. An index outside the valid range raises IndexError.
import numpy as np
a = np.arange(12).reshape(3, 4)
try:
a[3, 0]
except IndexError as e:
print(e) # index 3 is out of bounds for axis 0 with size 3
try:
a[0, 1, 2]
except IndexError as e:
print(e) # too many indices for array: array is 2-dimensional, but 3 were indexedThe first message names the axis and its size, so you can see which position is wrong. The second means you gave more integers than the array has axes. Check a.ndim and a.shape before debugging further.
Summary table
| Expression on `a` with shape `(3, 4)` | Result shape | Result |
|---|---|---|
| `a[1, 2]` | scalar | one element |
| `a[1]` | `(4,)` | one row |
| `a[-1]` | `(4,)` | last row |
| `a[3, 0]` | none | `IndexError` |
Exercise
Given c = np.arange(60).reshape(3, 4, 5), what is the shape of c[2, 1], and what is the value of c[-1, -1, -1]?
Show answer
c[2, 1] uses two integers on a 3-D array, so one axis remains and the shape is (5,). c[-1, -1, -1] is the last element along every axis, which is element 59, so the value is 59.
Exercise
You run a[2, 4] on an array with shape (3, 4). Which exception do you get, and which axis does the message name?
Show answer
You get IndexError. The message names axis 1, because the column index 4 is out of bounds for size 4 (valid columns are 0 to 3 or -4 to -1).