Beginner: data foundations · Cleaning, exploring and visualising data · topic 16 of 62 · 30 min
NumPy: fast arrays of numbers
Explanation
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
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 columnsVectorisation: 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.
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]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".
bonus = np.array([5, 0, 2]) # extra marks per subject
print(marks + bonus)
# [[83 65 92]
# [93 72 97]]Boolean masks: filtering without loops
print(prices > 100) # [ True True False True]
print(prices[prices > 100]) # [120 250 480]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.
print(marks.mean(axis=0)) # [83. 68.5 92.5] per subject
print(marks.mean(axis=1)) # [77.67 85. ] roughly, per studentCommon 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.
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
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.
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)Practice (0/3 done)
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].
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.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- pandas basics: Series and DataFramesCleaning, exploring and visualising data · same module
- Cleaning messy dataCleaning, exploring and visualising data · same module
- Grouping, joining and reshapingCleaning, exploring and visualising data · same module
- Row and ColumnFlutter and Dart · Layouts
- Arrays and array methodsFrontend Web Development · JavaScript basics
- Network, broadcast and usable host rangeComputer Networking (CCNA level) · IPv4 addressing
Questions people ask about this
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
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.
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).
What does 10 / 2 give in Python 3?Related
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
- 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.
- Module 4 exam: Cleaning, exploring and visualising data · 12 questions · 25 min, without help. 6 topics of this module still to finish first.
- Then the next module, The ML workflow, regression and classification. 62 topics left in the course before the final exam.