Lesson 05
Indexing
Read and change single values in 1-D, 2-D, and 3-D arrays with positive and negative indices, and see what an invalid index raises.
Indexing gets one value out of an array. Positions start at 0 from the left and at -1 from the right. A 2-D array needs a row and a column. A 3-D array needs a block, a row, and a column.
1-D indexing
a[i] gives one value. Negative indices count from the end. An index past either end raises IndexError.
import numpy as np
a = np.array([40, 15, 72, 8, 63])
print(a[0], a[2], a[-1], a[-2])
try:
print(a[5])
except IndexError as error:
print("IndexError:", error)Output:
40 72 63 8
IndexError: index 5 is out of bounds for axis 0 with size 52-D indexing
Write m[row, col]. m[row][col] gives the same value in two steps, but the comma form is the usual one. Both indices can be negative.
import numpy as np
m = np.array([[11, 12, 13, 14],
[21, 22, 23, 24],
[31, 32, 33, 34]])
print(m[1, 2])
print(m[1][2])
print(m[-1, 0])
print(m[0, -1])Output:
23
23
31
143-D indexing
A 3-D array is a stack of 2-D blocks. Write t[block, row, col].
import numpy as np
t = np.arange(1, 13).reshape(2, 2, 3)
print(t)
print(t[1, 0, 2])
print(t[0, -1, -1])Output:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
9
6Change a value
An index on the left of = replaces that one value. The new value is converted to the array's dtype, so a float in an integer array loses its decimals.
import numpy as np
m = np.array([[1, 2], [3, 4]])
m[0, 1] = 20
m[-1, -1] = 9.8
print(m)Output:
[[ 1 20]
[ 3 9]]Key takeaways
-
Indices start at 0, and -1 is the last value
-
2-D:
m[row, col]. 3-D:t[block, row, col] -
An index past the end raises
IndexError -
Assigned values take the array's dtype
-
Next: Slicing
-
Previous: Random Arrays
Loading playground…
Check your understanding
Indexing Quiz
What is a[-1] for np.array([40, 15, 72])?
1 / 10