NumPy · Lesson 0.1

Why NumPy

What a NumPy array is, how it differs from a Python list, and why data tools are built on it.

NumPy is the Python library for fast maths on lots of numbers at once. pandas, scikit-learn and most data tools are built on top of it. Every code box here runs real NumPy in your browser.

Practices ask you to store your answer in a variable called result, and the check compares it with the answer.

1A list versus an array

np.array([...]) turns a list into an array. Maths on an array happens to every value, while the same maths on a list does something else entirely.

import numpy as np

prices = [4, 10, 7]
print(prices * 2)
arr = np.array(prices)
print(arr * 2)
NumPy (illustrative numbers)

Practice

Each value in minutes is how long a task took. Every task needs 5 more minutes of setup. Store the new times, as an array, in result.

import numpy as np

minutes = np.array([12, 30, 45, 8])
result = ...
NumPy (illustrative numbers)

2Two arrays together

Two arrays of the same length combine value by value: the first with the first, the second with the second, and so on. No loop needed.

import numpy as np

prices = np.array([4.5, 10.0, 7.25])
units = np.array([3, 1, 4])
revenue = prices * units
revenue
NumPy (illustrative numbers)

Practice

units is how many of each item sold and unit_cost is what each one cost to make. Store the total cost for each item (units times unit cost) in result.

import numpy as np

units = np.array([20, 5, 12, 40])
unit_cost = np.array([1.5, 8.0, 3.25, 0.5])
result = ...
NumPy (illustrative numbers)

3One type for every value

Every value in an array has the same type, its dtype. Mix whole numbers with a decimal and NumPy turns them all into decimals (float64).

import numpy as np

print(np.array([1, 2, 3]).dtype)
print(np.array([1, 2, 3.5]).dtype)
print(np.array([1, 2, 3.5]))
NumPy (illustrative numbers)

Practice

Make an array from [True, 2, 3] and store the name of its dtype (a string like "float64") in result.

import numpy as np

result = ...
NumPy (illustrative numbers)

4Why it's faster

A Python loop handles one number at a time. NumPy runs the whole calculation in fast compiled code, so it's usually many times quicker (your exact timings will differ).

import time
import numpy as np

numbers = list(range(1_000_000))
start = time.perf_counter()
total = sum(n * n for n in numbers)
middle = time.perf_counter()
arr = np.array(numbers)
total_np = (arr * arr).sum()
end = time.perf_counter()
print(f"loop: {middle - start:.3f}s  numpy: {end - middle:.3f}s  same answer: {total == total_np}")
NumPy (illustrative numbers)

Practice

Using an array (no loop), store the sum of the squares of the whole numbers from 1 to 1000.

import numpy as np

result = ...
NumPy (illustrative numbers)