NumPy Math · Exercises
Data

NumPy Math Exercises

4 exercises that build on the NumPy Math and Broadcasting lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: NumPy maths applies functions and summaries to whole arrays, and broadcasting lets arrays of different shapes work together by stretching the smaller one, so you can standardise, rescale and combine data without writing loops. By the end you can use ufuncs and aggregations with axis, predict how broadcasting will combine two shapes, reshape arrays, multiply matrices with @, standardise data into z-scores, and handle nan values and dtype overflow. You will practise: Balance after each year; Predict axis, broadcasting and reshape; Fix the row percentages; Z-scores that ignore missing data.

0 / 4 completed

NumPy Math practice exercises

1. Balance after each year

Write code Easy

Write a function yearly_balances(start, rate, years) that returns a NumPy array with the balance at the end of each year, from year 1 to years, rounded to 2 decimal places. A balance grows by start * (1 + rate) ** year. Do it without a loop: build the years with np.arange and let NumPy do the power for all of them at once.

Your code
import numpy as np

def yearly_balances(start, rate, years):
    pass

print(yearly_balances(1000, 0.10, 3))

2. Predict axis, broadcasting and reshape

Predict the output Medium

Read the code and type exactly what it prints. NumPy prints arrays with spaces instead of commas, and a 2-D array on several lines.

Read this code
import numpy as np

grid = np.array([[1, 2, 3],
                 [4, 5, 6]])
print(grid.sum(axis=0))
print(grid.sum(axis=1))
print(grid + np.array([10, 20, 30]))
print(grid.reshape(3, 2)[:, 0])
print(grid.T.shape)

3. Fix the row percentages

Fix the bug Medium

row_shares(counts) should divide every row of the 2-D array counts by that row's total, so each row of the result adds up to 1. It crashes with a ValueError about broadcasting. Fix the function so it works for any number of rows and columns.

Your code
import numpy as np

def row_shares(counts):
    totals = counts.sum(axis=1)
    return counts / totals

votes = np.array([[30, 10, 60],
                  [5, 5, 10]])
print(np.round(row_shares(votes), 2))

4. Z-scores that ignore missing data

Write code Hard

Write clean_z(values, limit) that returns the z-scores of a 1-D float array, (x - mean) / std, and then clips them to the range -limit to limit. The array may contain nan values: the mean and standard deviation must be calculated ignoring them, and the nan entries must stay nan in the result. Use NumPy's own std (it divides by n).

Your code
import numpy as np

def clean_z(values, limit):
    # z-scores that ignore nan, then clip to [-limit, limit]
    pass

readings = np.array([2.0, 4.0, np.nan, 6.0])
print(clean_z(readings, 1))

Next lessonPandas Basics

More NumPy Math and Broadcasting examples · All Python exercises