Indexing and memory

Indexing and slicing in one and two dimensions, views versus copies, and boolean masks for filtering and updating.

About 5 hours of study

Learning objectives

Lessons

  1. 1

    Indexing and slicing Intermediate

    Reading elements and sub-arrays: one index per axis separated by commas, negative indices, slices with start, stop and step on each axis, and how an integer index drops a dimension while a slice keeps it.

  2. 2

    Views and copies Intermediate

    Why slicing a NumPy array does not copy it, how writes through a view change the original, which operations copy (fancy indexing, masks, copy, astype), and how to tell them apart.

  3. 3

    Boolean masks and where Intermediate

    Comparisons that give arrays of True and False, selecting with a mask, combining conditions with &, | and ~, counting matches, np.where, and assigning through a mask.

Module practice

Module quiz

1. For a 2-D array m, what does m[1] give?
2. A basic slice like a[1:4] returns…
3. What does a[a > 0] return?
4. Which indexing returns a copy?
5. How do you combine two masks with 'and'?
6. b = a[::2]; b[0] = 99. What happens to a?

‹ Arrays and typesVectorised computing ›