Python, from Zero, for AILesson 73 of 89

Module 8 · Numbers in bulk: NumPy, pandas and the vector under every model

Masks, where, and the slice that is not a copy

In this lesson

  • 8 min read
  • 7 reading sections
  • Knowledge check
  • Lesson 4 of 10 in this chapter

This chapter’s goalLoad a messy CSV into pandas, clean its missing values and types, group and join it into the table a question needs, convert it to a NumPy array of the right shape and dtype, compute cosine similarity between one vector and a hundred thousand in a single vectorised expression, plot the result to a file, and explain from memory layout why the array version runs a hundred times faster than the loop it replaced.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:43Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 9Free · no account needed
Lesson steps

Selecting with a condition

Python
scores = np.array([0.91, 0.12, 0.77, 0.45, 0.98])
mask = scores > 0.5
mask                 # [ True, False,  True, False,  True]
scores[mask]         # [0.91, 0.77, 0.98]
mask.sum()           # 3 — True counts as 1

A comparison on an array produces a boolean array of the same shape, and indexing with it keeps the elements where it is True. Two lines replace a loop with an if, and they run at NumPy speed. Combine conditions with &, | and ~, each side in brackets: and/or do not work on arrays, and forgetting the brackets makes & bind tighter than > and raise a confusing error:

Python
scores[(scores > 0.3) & (scores < 0.9)]      # [0.77, 0.45]
scores[~mask]                                # [0.12, 0.45]

Assignment through a mask changes only the selected elements:

Python
scores[scores < 0.2] = 0.0

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘Masks, where, and the slice that is not a copy’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/masks-views-and-copies (Accessed: 21 November 2026).