Skip to content
NumPy

Indexing and Slicing

Slice arrays and index with boolean masks.

By EZ4Code Team
indexingslicingmask

Code

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)

Explanation

NumPy slicing mirrors Python lists but applies to each axis, so a[1:3, 2:4] selects a sub-block. Boolean masks select elements where a condition holds, returning a flattened copy. Fancy indexing with integer arrays selects rows or columns in any order, and where() maps values element-wise.

More NumPy Snippets