Skip to content

Beginner: data foundations · Cleaning, exploring and visualising data · topic 16 of 62 · 30 min

NumPy: fast arrays of numbers

Explanation

NumPy is the Python library for fast maths on large lists of numbers, called arrays. Instead of writing a loop, you write one expression and NumPy applies it to every element at once (vectorisation). Almost every data and ML library in Python is built on NumPy arrays.

Why not just Python lists?

A Python list can hold anything: numbers, text, other lists. That flexibility makes it slow for maths, because Python checks the type of every item in a loop. A NumPy array holds one type of value (for example, 64-bit decimal numbers) packed tightly in memory, and its maths runs in fast compiled code. On a million numbers, a NumPy sum is often 10 to 100 times faster than a Python loop.

Creating arrays

python
import numpy as np

prices = np.array([120, 250, 99, 480])
print(prices)          # [120 250  99 480]
print(prices.dtype)    # int64 (on most systems)
print(prices.shape)    # (4,)

marks = np.array([[78, 65, 90],
                  [88, 72, 95]])
print(marks.shape)     # (2, 3): 2 rows, 3 columns
shape tells the size along each dimension; dtype is the type of every element. Shown only: install NumPy with pip install numpy.

Vectorisation: maths on the whole array

Vectorisation means writing an operation once for the whole array instead of looping. prices * 1.18 adds 18% GST to every price. Two arrays of the same shape can be added element by element: the first with the first, the second with the second.

python
with_gst = prices * 1.18
print(with_gst)        # [141.6  295.   116.82 566.4 ]
print(prices + np.array([10, 10, 10, 10]))   # [130 260 109 490]
No loop needed. The same idea in plain Python is [p * 1.18 for p in prices].

Broadcasting

Broadcasting is NumPy's rule for combining arrays of different shapes. A single number is "stretched" to match the array, which is why prices * 1.18 works. A row of 3 numbers can be added to every row of a (2, 3) table. If the shapes cannot be matched, NumPy raises an error such as "operands could not be broadcast together".

python
bonus = np.array([5, 0, 2])      # extra marks per subject
print(marks + bonus)
# [[83 65 92]
#  [93 72 97]]
The 3 bonus values are added to each of the 2 rows.

Boolean masks: filtering without loops

python
print(prices > 100)              # [ True  True False  True]
print(prices[prices > 100])      # [120 250 480]
A comparison gives an array of True/False called a mask. Using the mask inside [ ] keeps only the True positions.

Axis: along rows or down columns

For a 2-D array, axis=0 means "down the rows" (one answer per column) and axis=1 means "across the columns" (one answer per row). marks.mean(axis=0) gives each subject's average; marks.mean(axis=1) gives each student's average.

python
print(marks.mean(axis=0))   # [83.  68.5 92.5]   per subject
print(marks.mean(axis=1))   # [77.67 85.  ] roughly, per student
Remember: the axis you name is the one that disappears.

Common mistakes

  • Writing Python loops over arrays out of habit. Fix: look for a vectorised expression first.
  • Using and / or with arrays: (a > 1 and a < 5) raises "truth value of an array is ambiguous". Fix: use & and | with brackets: (a > 1) & (a < 5).
  • Mixing up axis=0 and axis=1. Fix: check the .shape of the result.
  • Expecting arrays to grow like lists. np.append makes a full copy every time. Fix: build a Python list first, then convert once.
Tip: The tasks below practise each idea in plain Python, so they run in your browser. In real projects, the same ideas are one-line NumPy expressions.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

NumPy: fast arrays of numbers · 1/7

NumPy arrays

Meet NumPy, the library that makes number crunching in Python fast.

Prefer a video by a teacher? Find free videos on “numpy tutorial for beginners arrays broadcasting boolean indexing” on YouTube ↗

In real life: Weather data at scale

A weather data team stores hourly temperature readings for thousands of stations across India. With NumPy, converting all readings from Celsius to Fahrenheit, finding the hottest hour for each station (max along an axis) or flagging readings above 45 °C (a boolean mask) are single lines that run in a fraction of a second, even on crores of values.

python
readings = [[31.5, 38.0, 44.2], [29.0, 46.1, 41.3]]
hot = [[t for t in row if t > 45] for row in readings]
print(hot)
The plain-Python version of a boolean mask: shows [[], [46.1]].

Practice (0/3 done)

Task 1 · Code · Python

Write add_arrays(a, b) that adds two lists of numbers element by element, like NumPy's a + b. If the lengths differ, raise ValueError. Example: add_arrays([1, 2, 3], [10, 20, 30]) returns [11, 22, 33].

Task 2 · Code · Python

Write mask_filter(values, low, high) that keeps the values with low < value < high (both limits excluded), like values[(values > low) & (values < high)] in NumPy. Keep the original order.

Task 3 · Code · Python

Write column_means(rows) for a 2-D list (every row has the same length). Return a list with the mean of each column, rounded to 2 decimal places, like arr.mean(axis=0). For an empty list return [].

Quick quiz

Question 1

1.Why is a NumPy array faster than a Python list for maths?

Question 2

2.a = np.array([2, 4, 6]). What is a * 2?

Question 3

3.m has shape (100, 5): 100 customers, 5 features. What shape does m.mean(axis=0) have?

Question 4

4.Which correctly keeps values between 10 and 20?

Question 5

5.What is broadcasting?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Why is a NumPy array faster than a Python list for maths?

Answer: It stores one type of number tightly and runs the maths in compiled code

Fixed type plus compiled loops avoid Python's per-item overhead.

a = np.array([2, 4, 6]). What is a * 2?

Answer: [4, 8, 12]

Arrays multiply element by element. (A list times 2 would repeat the list.)

m has shape (100, 5): 100 customers, 5 features. What shape does m.mean(axis=0) have?

Answer: (5,)

axis=0 collapses the rows, leaving one mean per column: 5 values.

Which correctly keeps values between 10 and 20?

Answer: a[(a > 10) & (a < 20)]

Use & between masks, with each condition in brackets because & binds tightly.

What is broadcasting?

Answer: NumPy's rule for combining arrays of different but compatible shapes

It stretches a scalar or smaller array to match a bigger one when the shapes allow.

What is the main axis of a Column?Related

Answer: Vertical

Columns lay out vertically.

From Row and Column

Which method returns a new array with only the items that pass a test?Related

Answer: filter

filter keeps the items for which the callback returns true.

From Arrays and array methods

You need a queue in Python with fast removal from the front. What should you use?Related

Answer: collections.deque with popleft()

deque.popleft() is O(1); list.pop(0) is O(n).

From The real cost of Python and JavaScript built-ins

What does 10 / 2 give in Python 3?Related

Answer: 5.0

The / operator always returns a float, so 10 / 2 is 5.0.

From Numbers and maths

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 5 more topics in “Cleaning, exploring and visualising data” before its exam: pandas basics: Series and DataFrames, Cleaning messy data, Grouping, joining and reshaping, Exploratory data analysis (EDA), Visualising data honestly.
  2. Module 4 exam: Cleaning, exploring and visualising data · 12 questions · 25 min, without help. 6 topics of this module still to finish first.
  3. Then the next module, The ML workflow, regression and classification. 62 topics left in the course before the final exam.

← Previous: Hypothesis tests, p-values and A/B testing