Skip to main content
Albero Academy

Indexing, Slicing & Reshaping

Select and modify parts of an array, filter with boolean masks, and change shape — the skills you use in every analysis.

Chapter 2NumPy15 min readBeginner friendly
  • #NumPy
  • #Indexing
  • #Slicing

Getting data out of an array — a row, a column, everything above a threshold — is the day-to-day of analysis. NumPy's indexing is richer than a Python list's, and boolean masking in particular is the single most useful technique in this course.

1-D & 2-D indexing

indexing
a = np.array([10, 20, 30, 40])
a[0] # 10
a[-1] # 40 (last)
b = np.array([[1, 2, 3],
[4, 5, 6]])
b[0, 2] # 3 (row 0, col 2)
b[1] # [4 5 6] (whole row)

Slicing

Slicing uses start:stop:step per dimension. For 2-D, separate the row and column slice with a comma:

slices
b[:, 0] # first column of every row → [1 4]
b[0, :] # first row (all columns) → [1 2 3]
b[:, 1:3] # columns 1 and 2, all rows
a[::2] # every second element → [10 30]
# Slices can be assigned to — updates in place
b[:, 0] = 0 # zero out the first column

Boolean masks

Compare an array to a value and you get a boolean array; index with it to keep only the elements that pass. This replaces filtering loops entirely:

the most useful trick in NumPy
scores = np.array([55, 82, 47, 91, 68])
scores > 60 # [False True False True True]
scores[scores > 60] # [82 91 68] ← the passing scores
# Combine conditions with & (and) | (or) — wrap each in ()
scores[(scores > 50) & (scores < 90)] # [55 82 68]
# Assign through a mask
scores[scores < 60] = 0 # fail → 0

Reshaping

changing shape
a = np.arange(12) # [0 1 2 … 11]
a.reshape(3, 4) # 3 rows × 4 cols
a.reshape(4, -1) # -1 = "figure out this dimension" → 4×3
a.ravel() # flatten back to 1-D
b.T # transpose (swap rows/columns)

Views vs copies

A slice is a view — it shares memory with the original, so writing to the slice changes the source. When you need an independent array, call .copy():

don't get caught out
a = np.array([1, 2, 3, 4])
view = a[1:3]
view[0] = 99 # a is now [1 99 3 4] — the slice was a view!
safe = a[1:3].copy()
safe[0] = 0 # a is unchanged

Practice

From a 4×4 array of the numbers 0–15 (use arange(16).reshape(4, 4)): extract the last column, every value greater than 8, and the top-left 2×2 block. Then set every even number to zero with a boolean mask.

Key takeaways

  1. 01Index 2-D arrays with [row, col]; a bare row index returns the whole row.
  2. 02Slice per dimension with start:stop:step; slices can be assigned to in place.
  3. 03Boolean masks (arr[arr > x]) filter without loops — combine conditions with & and | inside ().
  4. 04reshape changes shape (use -1 to infer a dimension); .T transposes; .ravel flattens.
  5. 05A slice is a view sharing memory — use .copy() when you need an independent array.