Indexing, slices, and masks
2.5.5
Read or update array values by position, condition, and dimension.
On this page
Index by axis
Use array[row, column] to select a cell in a 2D array. An index of -1 means the last position, and a colon can select every position along that axis.
import numpy as np
data = np.array([[10, 3, 7], [12, 4, 8]])
print(data[0, -1])
print(data[:, -1].tolist())
Example output
7 [7, 8]
Apply a Boolean mask
A comparison yields a Boolean array. Wrap each comparison in parentheses when combining masks with & or |. Use ~ to invert a mask.
import numpy as np
marks = np.array([80, 32, 50, 91, 67])
mask = (marks >= 50) & (marks <= 80)
print(marks[mask].tolist())
Example output
[80, 50, 67]
Know when memory is shared
Basic slicing returns views of array data. Integer-array and Boolean-array indexing return copies when used to retrieve values. Use copy() when you need an independent result.
import numpy as np
a = np.array([10, 20, 30])
b = a[:2]
b[0] = 99
print(a.tolist())
Example output
[99, 20, 30]