NumPy Tutorial 03: Indexing, Masking, and Reshaping

Download Notebook

Download this notebook

import numpy as np

1. Basic slicing returns views

Changes on a slice may affect the original array.

a = np.arange(10)
s = a[2:7]
s[:] = -1
print('slice:', s)
print('original changed:', a)
slice: [-1 -1 -1 -1 -1]
original changed: [ 0  1 -1 -1 -1 -1 -1  7  8  9]

2. Fancy indexing returns copies

Integer-array indexing produces a copy, not a view.

a = np.arange(10)
picked = a[[1, 3, 5, 7]]
picked[:] = 100
print('picked:', picked)
print('original unchanged:', a)
picked: [100 100 100 100]
original unchanged: [0 1 2 3 4 5 6 7 8 9]

3. Boolean masking

Boolean masks are expressive for filtering and assignment.

rng = np.random.default_rng(0)
x = rng.normal(size=12)
mask = x > 0

print('x:', np.round(x, 3))
print('positive values:', np.round(x[mask], 3))

x2 = x.copy()
x2[x2 < 0] = 0
print('negative clipped to 0:', np.round(x2, 3))
x: [ 0.126 -0.132  0.64   0.105 -0.536  0.362  1.304  0.947 -0.704 -1.265
 -0.623  0.041]
positive values: [0.126 0.64  0.105 0.362 1.304 0.947 0.041]
negative clipped to 0: [0.126 0.    0.64  0.105 0.    0.362 1.304 0.947 0.    0.    0.    0.041]

4. Multi-dimensional indexing

Use row/column selectors and : slices to target blocks.

m = np.arange(1, 17).reshape(4, 4)
print('m:\n', m)
print('element (2,3):', m[2, 3])
print('second column:', m[:, 1])
print('middle block:\n', m[1:3, 1:3])
m:
 [[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]]
element (2,3): 12
second column: [ 2  6 10 14]
middle block:
 [[ 6  7]
 [10 11]]

5. Reshape, transpose, and axis semantics

Axis 0 is rows, axis 1 is columns for 2D arrays.

x = np.arange(24)
m = x.reshape(2, 3, 4)

print('shape:', m.shape)
print('sum axis=0 shape:', m.sum(axis=0).shape)
print('sum axis=1 shape:', m.sum(axis=1).shape)
print('sum axis=2 shape:', m.sum(axis=2).shape)
shape: (2, 3, 4)
sum axis=0 shape: (3, 4)
sum axis=1 shape: (2, 4)
sum axis=2 shape: (2, 3)

6. Practice

  1. Build a 6x6 matrix from 1 to 36.

  2. Extract all even numbers using a boolean mask.

  3. Replace diagonal elements with 0.