Module 4 · NumPy: Fast Maths on Arrays · Lesson 14 of 51

Aggregations, axes, broadcasting and simulation

sum, mean, std and percentiles along an axis, broadcasting arrays of different shapes, np.where, and random numbers to simulate a busy day.

In this lesson · about 40 minutes

  • Aggregate along axis=0 and axis=1
  • Predict when broadcasting works and what it does
  • Simulate random outcomes with a seeded random generator

Try it · data lab

NumPy arrays: axes, reshape and broadcasting

Quarterly sales (in $1,000s) for three branches. See which way axis=0 and axis=1 run, reshape the numbers, and combine arrays of different shapes.

1 · Collapse along an axis

Q1Q2Q3Q4
Downtown12151418
Riverside891110
Campus20221925
↓ sum40464453

NumPy

sales.sum(axis=0)
# → array([40, 46, 44, 53])   shape (4,)
axis=0 squashes the rows together: one answer per column (per quarter). The axis you name is the one that disappears.

2 · Reshape the same 12 numbers

12151418
891110
20221925

sales.reshape(3,4) reads the numbers row by row (12, 15, 14, 18, 8, …) and pours them into the new shape. The data never changes, only how it is arranged.

3 · Broadcasting: combine arrays of different shapes

NumPy

sales + 2
14171620
10111312
22242127
A single number is stretched to every cell.

Aggregations

a.sum(), .mean(), .min(), .max(), .std(), np.median(a), np.percentile(a, 90), a.argmax() (position of the biggest), a.cumsum() (running total). On 2-D arrays, add axis=0 (down the rows, one answer per column) or axis=1 (across the columns, one per row). The axis you name is the one that disappears.

Broadcasting rules

NumPy compares shapes from the right. Two sizes fit if they are equal or one of them is 1. So (3, 4) works with (4,) and with (3, 1), but not with (3,). Use .reshape(3, 1) to turn a row into a column.

np.where: if-else on arrays

np.where(sales > 15, "high", "normal") labels every value at once.

Random numbers

rng = np.random.default_rng(42)        # seeded: same numbers every run
rng.integers(1, 7, size=10)            # ten dice rolls
rng.normal(loc=50, scale=10, size=5)   # bell-curve values
rng.choice(["Card", "App", "Cash"], size=5, p=[0.55, 0.3, 0.15])

A seed makes "random" results repeatable, so your analysis can be checked by others. Always seed when results go in a report.

Simulate 10,000 café mornings

Each morning, between 40 and 80 customers arrive and each spends a random amount around $6. How often does the morning bring in over $400?

Exercise

Totals per branch and per quarter

Set per_quarter to the total for each quarter (one value per column), per_branch to the mean per branch (one per row), and best_branch to the row index of the branch with the highest total (use argmax).

Exercise

Share of each branch's year

Divide every value in sales by its row's total, so each row shows the share of that branch's year earned in each quarter. Round to 3 decimals and store it in share. Hint: the row totals need shape (3, 1).

Exercise

Simulate dice: the law of large numbers

With rng = np.random.default_rng(1), roll a die 10,000 times using rng.integers(1, 7, size=10000) and store the rolls in rolls. Set share_six to the share of rolls that are 6. It should be close to 1/6 ≈ 0.167.

Flashcards

Module 4 flashcards

0 of 9 known

Say the answer out loud, flip the card, then be honest: cards you miss come back at the end.

9 left in the deck

Practice exam

Module 4 checkpoint

8 questions, 10 minutes.

  • 8 questions · 10 minutes
  • No feedback until you submit. Flag questions to come back to them.
  • Aim for 85% or better before you move on. The real exam's 750 out of 900 is roughly 80–83%.

Exercises solved: 0 of 3

Tip: solve each exercise first. Press Check to test your code.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.