Quick, think about this for a sec
This lesson steps up from Practice: Arrays & Indexing, with 4 tasks that combine broadcasting, axis aggregation, reshaping, linear algebra, and the random module from the Intermediate/Advanced chapters. Each task builds on the basic skills from Part 1 and connects them to real-world data patterns — price plus tax, normalization, matrix multiplication. Work through the tasks in order and you'll come away with the confidence to rebuild an entire NumPy project on your own.
Exercises
Task 1: Build a (3, 4) price matrix for 4 products across 3 stores, then use broadcasting to add a 1D array of different tax rates per column ([0.05, 0.08, 0.05, 0.10]). Task 2: On the price matrix, compute both axis=0 (store-wise sum) and axis=1 (product-wise sum), then use np.argmax() to find the index of the highest-priced product. Task 3: Set np.random.seed(), generate a random 2D array with np.random.rand(4, 4), and normalize it using the formula (array - array.mean()) / array.std(). Task 4: Multiply a shape (2, 3) matrix with a shape (3, 2) matrix using the @ operator (or np.dot()), and confirm the resulting shape.
Code Example
import numpy as np
# Task 1: broadcasting tax onto price matrix
prices = np.array([
[1000, 2000, 1500, 3000],
[1100, 1900, 1600, 2800],
[950, 2100, 1550, 3200]
])
tax_rate = np.array([0.05, 0.08, 0.05, 0.10])
prices_with_tax = prices + (prices * tax_rate)
print("prices with tax:\n", prices_with_tax)
# Task 2: axis aggregation + argmax
store_totals = prices.sum(axis=1)
product_totals = prices.sum(axis=0)
top_product_index = np.argmax(product_totals)
print("store totals:", store_totals)
print("product totals:", product_totals, "top index:", top_product_index)
# Task 3: random + normalization
np.random.seed(1)
random_grid = np.random.rand(4, 4)
normalized = (random_grid - random_grid.mean()) / random_grid.std()
print("normalized:\n", normalized)
# Task 4: matrix multiplication
a = np.arange(6).reshape(2, 3)
b = np.arange(6).reshape(3, 2)
result = a @ b
print("result shape:", result.shape)
print(result)
All 4 tasks will print out: the price matrix with tax added, store/product totals along with the top index, an array normalized to near-zero mean, and the result of a shape (2, 2) matrix multiplication.Try it in 5 minutes
Change Task 4's a and b matrices to the same shape, (2, 3) and (2, 3), then read the error message from a @ b and figure out why it fails (5 minutes).
A quick word of caution
a @ b (matrix multiplication) and a * b (element-wise multiplication) are completely different operations — matrix multiplication requires a.shape[1] == b.shape[0].