Skip to content
NumPy

Indexing and Slicing

Slice arrays and index with boolean masks.

#indexing#slicing#mask

Code

numpy
import numpy as np

a = np.arange(20).reshape(4, 5)

# Slicing rows and columns
first_row = a[0, :]
sub = a[1:3, 2:4]

# Boolean mask
mask = a > 10
gt_ten = a[mask]

# Fancy indexing
cols = a[:, [0, 2, 4]]
rows = a[[0, 2], :]

# Where condition
clipped = np.where(a > 15, -1, a)
print(sub, gt_ten, clipped)