Indexing and Slicing
Access single elements or whole sub-sections of an array with square brackets.
Arrays are indexed like lists, but multi-dimensional arrays use a comma between axes: a[row, col].
Slicing
start:stop:step selects a range. For 2D arrays you slice each axis: a[0:2, 1:3].
Boolean indexing
A condition produces a mask of True/False that selects matching elements — the heart of filtering data.
Example
import numpy as np
a = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(a[1, 2]) # 6 (row 1, col 2)
print(a[0]) # [1 2 3] (first row)
print(a[:, 1]) # [2 5 8] (middle column)
print(a[a > 5]) # [6 7 8 9] (boolean mask)When to use it
- A data scientist slices the first 1000 rows of a feature matrix with X[:1000] to create a quick sanity-check mini-dataset.
- An engineer uses boolean indexing to extract all rows where a prediction score exceeds a confidence threshold of 0.9.
- A computer-vision pipeline uses 2D slicing to crop a region of interest from an image array before passing it to a detector.
More examples
Basic 1D and 2D indexing
Accesses individual elements and a slice from a 1D array using Python's standard indexing syntax.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # first element
print(arr[-1]) # last element
print(arr[1:4]) # slice: 20, 30, 402D matrix row and column slicing
Slices rows, columns, and rectangular sub-blocks from a 2D matrix using comma-separated index expressions.
import numpy as np
M = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(M[1, :]) # second row
print(M[:, 2]) # third column
print(M[0:2, 1:]) # top-right 2x2 blockBoolean mask indexing
Uses a boolean condition as a mask to filter an array, returning only elements that satisfy the condition — a common ML post-processing step.
import numpy as np
scores = np.array([0.55, 0.92, 0.78, 0.95, 0.41])
high_conf = scores[scores > 0.85]
print(high_conf) # [0.92, 0.95]
Discussion