Indexing and Slicing Arrays
Indexing 1D arrays
Section titled “Indexing 1D arrays”import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # 10
print(arr[3]) # 40
print(arr[-1]) # 50Slicing 1D arrays
Section titled “Slicing 1D arrays”Slicing uses start:stop:step (stop is excluded).
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]) # reverseIndexing 2D arrays (rows/columns)
Section titled “Indexing 2D arrays (rows/columns)”McKinney’s tip for reading 2D arrays: think of axis 0 as the “rows” and axis 1 as the “columns.”
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 columnSub-arrays (2D slicing)
Section titled “Sub-arrays (2D slicing)”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)Views vs copies (important)
Section titled “Views vs copies (important)”Many slices are views (they share memory).
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
sub = arr[1:4] # view
sub[0] = 999
print(arr) # original changedTo force a copy:
sub = arr[1:4].copy()Boolean indexing (masking)
Section titled “Boolean indexing (masking)”Boolean indexing is extremely useful for analytics filtering.
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]Combine conditions
Section titled “Combine conditions”Use parentheses and & / | — the Python keywords and/or do not work with Boolean arrays.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[(arr >= 20) & (arr <= 40)])Fancy indexing
Section titled “Fancy indexing”Select multiple specific indices using a list/array. Unlike slicing, fancy indexing always copies the data.
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[[0, 2, 4]])flowchart LR A["ndarray"] --> B["Basic index
arr[2]"] A --> C["Slice
arr[1:4]"] A --> D["Boolean mask
arr[arr > 25]"] A --> E["Fancy index
arr[[0, 2, 4]]"] B --> F["Scalar or view"] C --> F D --> G["Copy"] E --> G
Continue to: Shape Manipulation & Reshape to learn how to change dimensions safely.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Slice a 2D Sub-array
Section titled “Exercise 1 – Slice a 2D Sub-array”Exercise 2 – Filter with a Boolean Mask
Section titled “Exercise 2 – Filter with a Boolean Mask”Exercise 3 – A View Changes the Original
Section titled “Exercise 3 – A View Changes the Original”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading