Skip to content

Indexing and Slicing Arrays

1d
import numpy as np
 
arr = np.array([10, 20, 30, 40, 50])
 
print(arr[0])   # 10
print(arr[3])   # 40
print(arr[-1])  # 50

Slicing uses start:stop:step (stop is excluded).

slice
import numpy as np
 
arr = np.array([10, 20, 30, 40, 50])
 
print(arr[1:4])   # [20 30 40]
print(arr[:3])    # [10 20 30]
print(arr[::2])   # [10 30 50]
print(arr[::-1])  # reverse

McKinney’s tip for reading 2D arrays: think of axis 0 as the “rows” and axis 1 as the “columns.”

2d
import numpy as np
 
mat = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])
 
print(mat[0, 0])  # 1
print(mat[1, 2])  # 6
print(mat[2, :])  # full row
print(mat[:, 1])  # full column
subarray
import numpy as np
 
mat = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])
 
# rows 0..1 and cols 1..2
sub = mat[0:2, 1:3]
print(sub)
sketch Highlighting a 2D slice p5.js
mat[0:2, 1:3] selects rows 0-1 and columns 1-2 — the highlighted rectangle of the grid.

Many slices are views (they share memory).

view
import numpy as np
 
arr = np.array([1, 2, 3, 4, 5])
sub = arr[1:4]   # view
sub[0] = 999
 
print(arr)  # original changed

To force a copy:

copy
sub = arr[1:4].copy()

Boolean indexing is extremely useful for analytics filtering.

mask
import numpy as np
 
arr = np.array([10, 20, 30, 40, 50])
mask = arr > 25
 
print(mask)      # [False False  True  True  True]
print(arr[mask]) # [30 40 50]

Use parentheses and & / | — the Python keywords and/or do not work with Boolean arrays.

mask2
import numpy as np
 
arr = np.array([10, 20, 30, 40, 50])
print(arr[(arr >= 20) & (arr <= 40)])

Select multiple specific indices using a list/array. Unlike slicing, fancy indexing always copies the data.

fancy
import numpy as np
 
arr = np.array([10, 20, 30, 40, 50])
print(arr[[0, 2, 4]])
diagram Four ways to select data mermaid
NumPy offers four selection styles, each returning a different shape and a view-or-copy behavior.

Continue to: Shape Manipulation & Reshape to learn how to change dimensions safely.

Exercise 3 – A View Changes the Original

Section titled “Exercise 3 – A View Changes the Original”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading