DS 208 · Week 5

Scientific Computing with NumPy

Computation on thousands of numbers at once, in one line and much faster than an equivalent Python loop.

Programming for Data Science · University of the Philippines Cebu

Outline

Arrays, operations and indexing

Previous session

Loops become slow on large data

A Python for loop over a million prices is slow and verbose. NumPy moves that work into fast C code and expresses it in a single line.

“C code” means code written in the C language and translated to machine instructions ahead of time. NumPy’s inner loops are already written in C and are called from Python.

Limitation

List and loop: many lines, and slow on realistic dataset sizes.

Advantage

Array and one operation: shorter, clearer and often 50× faster.

About the tool

NumPy grew out of two earlier libraries

1995

Numeric

Jim Hugunin writes Python’s first array library.

Early 2000s

Numarray

A rewrite, built to handle Hubble Space Telescope images.

2005–06

NumPy

Travis Oliphant merges the two; NumPy 1.0 is released in 2006.

2024

NumPy 2.0

The first major version in 18 years.

SourceHarris et al., “Array programming with NumPy,” Nature 585, 357–362 (2020); numpy.org/about; NumPy 2.0.0 release on PyPI, 16 June 2024

About the tool

How widely NumPy is used

SourceDownloads: pypistats.org, without mirrors, retrieved 11 Oct 2026; science uses: Harris et al., Nature 585 (2020); governance: numpy.org/about

Key terms

Nine terms introduced this week

array (ndarray)

NumPy’s container: many values of one type, stored side by side. “ndarray” = n-dimensional array, its full name.

e.g. np.array([1, 2, 3])

element

One value inside an array — like one cell of a spreadsheet.

e.g. in [10, 20, 30], 20 is the element at position 1

dtype

The data type every element shares: whole numbers, decimals, text…

e.g. int64 (whole numbers), float64 (decimals)

dimension

One direction of movement: a row of numbers has 1 dimension, a table has 2 (down and across).

e.g. [[1, 2], [3, 4]] is 2-D

shape

How many elements along each dimension, written as a tuple (rows, columns).

e.g. (2, 3) = 2 rows, 3 columns

axis

A dimension referred to by number when summarising: axis=0 goes down the rows, axis=1 across the columns.

e.g. m.sum(axis=0) gives one total per column

vectorised operation

One line of maths that applies to every element at once, with no Python loop.

e.g. prices * 1.12 adds VAT to every price

broadcasting

NumPy stretching a smaller array (or single number) to match a bigger one so they can be combined.

e.g. np.array([1, 2, 3]) + 10 gives [11 12 13]

boolean mask

An array of True/False, one per element, used to keep only the True ones.

e.g. temps[temps > 30] keeps the hot days

Runnable code

Code on these slides runs in the browser

A code block with a ▶ Run / Edit button opens in an editor. The code can be changed and run again; Reset restores the original. The exercises in this deck all work this way.

First run

The first run downloads Python and NumPy into the page, which takes about ten seconds. Later runs start at once.

Key terms

browser Python
a complete Python (called Pyodide) running inside the web page; nothing is installed and the code is not sent to a server
32-bit
the browser’s Python stores whole numbers in 32 bits, so arrays show int32 where the slides show int64

Printed outputs on the slides come from the lecture laptop (64-bit Python, NumPy 2). In the browser, timings and a few type names differ; the comparisons, not the exact numbers, are the point.

import sys print("NumPy version:", np.__version__) print("64-bit Python:", sys.maxsize > 2**32) a = np.array([1, 2, 3]) print(a * 2, a.dtype) NumPy version: 2.5.3 64-bit Python: True [2 4 6] int64
  • np.__version__the installed NumPy version: 2.5.3 on the laptop, 1.26.4 in the browser
  • sys.maxsize > 2**32True on a laptop’s 64-bit Python, False in the browser’s 32-bit one
  • [2 4 6] int64the same array in both places; the browser prints int32
Part A

The array

Many numbers of one type, stored together.

Weeks 2–3 stored numbers in a list and processed them with a loop. This part introduces the array, which stores the same numbers so that maths runs on all of them at once.

List vs array

A list holds any type; an array holds one numeric type

A list can mix types and is flexible but slow for maths. An array (NumPy calls it an ndarray, “n-dimensional array”) stores one type in a tight block, so operations run in bulk. Each value in it is an element.

import numpy as np nums = [1, 2, 3] # a Python list a = np.array(nums) # a NumPy array a # array([1, 2, 3])
  • import numpy as npload the NumPy library under its usual nickname np (an alias, week 4)
  • a = np.array(nums)build an array from the list: the same three numbers in a new container
  • array([1, 2, 3])how a notebook shows an array; the word array indicates that it is not a list
Memory layout

Why array operations are fast

Python list 3 pointers float 1.0 float 2.0 float 3.0 A million numbers: about 32 MB a pointer plus a separate 24-byte object for each NumPy array one unbroken block of memory 1.0 8 bytes 2.0 8 bytes 3.0 8 bytes A million numbers: 8 MB 1,000,000 × 8 bytes, and nothing else
Exercise · 3 min

Measuring the memory of a list and an array

The previous slide states that a list of a million floats needs about four times the memory of the array. sys.getsizeof measures it.

Tasks

  1. Predict both sizes in MB.
  2. Select ▶ Run / Edit and run the code.
  3. Change 1_000_000 to 10_000. Does the ratio change?

Result on the lecture laptop (select to reveal)

List 32.4 MB, array 8.0 MB: four times as much, at any size. The browser’s 32-bit Python stores smaller pointers and floats, so its list measures 20.2 MB.

import sys big_list = [i * 0.5 for i in range(1_000_000)] big = np.array(big_list) pointers = sys.getsizeof(big_list) numbers = sum(sys.getsizeof(x) for x in big_list) print(f"list : {(pointers + numbers) / 1e6:.1f} MB") print(f"array: {big.nbytes / 1e6:.1f} MB")
  • big_list = [i * 0.5 …]a million made-up decimals: 0.0, 0.5, 1.0, … (1_000_000 is 1000000; Python ignores the underscores)
  • sys.getsizeof(big_list)bytes used by the list itself: only its pointers
  • sum(sys.getsizeof(x) for x in big_list)like a comprehension without brackets: adds up the size of every float the pointers lead to (24 bytes each)
  • / 1e6bytes to megabytes (MB)
Timing comparison

A 60× speed-up on the same million numbers

Both versions add up the million numbers big_list and big from the memory exercise. One loops in Python; the other calls .sum(), which is vectorised: one operation on the whole array, with no Python loop. time.perf_counter() reads a precise clock, and the difference between two readings is the time taken.

  • def with_loop():the loop sits inside a function: Python runs a loop in a function about 3× faster than the same lines at the top of a notebook, and timeit (next slide) needs a function anyway
  • (time.perf_counter() - start) * 1000clock after minus clock before = seconds taken; × 1000 gives milliseconds
  • numpy: 0.14 msone reading of a very fast call is rough: three re-runs gave 0.14, 0.22 and 0.32 ms. The next slide repeats the measurement

A benchmark compares like with like

Timing two versions of the same task is a benchmark. Both must give the same answer first: here both totals are 249999750000.0.

Key terms

time.perf_counter()
a clock, in seconds, for measuring durations (not the time of day)
ms
millisecond, a thousandth of a second; seconds × 1000 = ms
# big_list and big from the memory exercise import time def with_loop(): total = 0.0 for x in big_list: total += x return total start = time.perf_counter() # read the clock with_loop() loop_ms = (time.perf_counter() - start) * 1000 start = time.perf_counter() big.sum() np_ms = (time.perf_counter() - start) * 1000 print(f"loop : {loop_ms:.2f} ms") print(f"numpy: {np_ms:.2f} ms") loop : 6.76 ms numpy: 0.14 ms
Repeated measurement

timeit repeats a measurement and averages it

The standard-library module timeit calls a function many times and reports the total time. Dividing by the number of calls gives the time for one call, which is far steadier than a single reading.

The helper used in the exercises

time_ms(f) returns the average milliseconds per call of f. Every timed exercise in this deck uses it.

Key term

autorange()
timeit chooses the number of calls itself (1, 2, 5, 10, 20…) until they take at least 0.2 seconds in total

Timing one lap of a running track with a hand stopwatch is unreliable; timing twenty laps and dividing by twenty is not.

# big_list, big and with_loop() from the previous slides import timeit def time_ms(f): """Average milliseconds per call of f().""" calls, seconds = timeit.Timer(f).autorange() return seconds / calls * 1000 loop_ms = time_ms(with_loop) np_ms = time_ms(big.sum) print(f"loop : {loop_ms:.2f} ms") print(f"numpy: {np_ms:.3f} ms") print(f"NumPy is {loop_ms / np_ms:.0f}x as fast") loop : 6.85 ms numpy: 0.116 ms NumPy is 59x as fast
  • timeit.Timer(f).autorange()calls f repeatedly and returns two values: how many calls, and the total seconds they took
  • seconds / calls * 1000the average for one call, in milliseconds
  • time_ms(big.sum)no brackets after sum: the method itself is handed over, and time_ms calls it
Benchmark

The speed-up depends on the size of the array

How many times as fast NumPy’s arr.sum() is as a Python for loop 0× 20× 40× 60× 10 numbers: loop 0.10 µs, sum() 0.05 µs, arr.sum() 0.21 µs; NumPy 0.5× as fast as the loop 0.5× NumPy slower 10 loop 0.10 µs sum() 0.05 µs arr.sum() 0.21 µs 1,000 numbers: loop 6.8 µs, sum() 1.3 µs, arr.sum() 0.33 µs; NumPy 21× as fast as the loop 21× 1,000 loop 6.8 µs sum() 1.3 µs arr.sum() 0.33 µs 100,000 numbers: loop 0.70 ms, sum() 0.13 ms, arr.sum() 0.012 ms; NumPy 60× as fast as the loop 60× 100,000 loop 0.70 ms sum() 0.13 ms arr.sum() 0.012 ms 1,000,000 numbers: loop 7.0 ms, sum() 1.3 ms, arr.sum() 0.11 ms; NumPy 62× as fast as the loop 62× 1,000,000 loop 7.0 ms sum() 1.3 ms arr.sum() 0.11 ms 10,000,000 numbers: loop 69 ms, sum() 13 ms, arr.sum() 1.2 ms; NumPy 58× as fast as the loop 58× 10,000,000 loop 69 ms sum() 13 ms arr.sum() 1.2 ms

Measured on the lecture laptop with timeit, best of 7 repeats; Python 3.12, NumPy 2.5. µs = microsecond, a millionth of a second.

Exercise · 4 min

Finding the size at which NumPy overtakes sum()

This compares Python’s built-in sum() with arr.sum() at four sizes. A ratio below 1 means NumPy is slower.

Tasks

  1. Predict which wins at 10 numbers.
  2. Run the code (it takes a few seconds).
  3. Add 1_000 to the list of sizes, to narrow down where the ratio passes 1.

Result on the lecture laptop (select to reveal)

0.2× at 10 numbers, 0.7× at 100, 9.9× at 10,000 and 12× at 1,000,000. NumPy overtakes sum() somewhere between 100 and 10,000 numbers; for a handful of values a list is fine.

# time_ms(f) is the helper from the timeit slide for n in [10, 100, 10_000, 1_000_000]: nums = [i * 0.5 for i in range(n)] arr = np.array(nums) def list_sum(): return sum(nums) ratio = time_ms(list_sum) / time_ms(arr.sum) print(f"{n:>9,} numbers: NumPy is {ratio:5.1f}x as fast")
  • for n in [10, 100, 10_000, 1_000_000]:repeat the whole experiment once for each size
  • def list_sum():wraps sum(nums) in a function so that time_ms can call it
  • {n:>9,}format code: right-align in 9 characters, with thousands commas
Data types

An array has a single dtype

An array’s dtype (data type) is the one type every element shares. Lists allow mixed types; arrays do not. When NumPy must choose a common type, the result may not be the intended one.

Checking dtype when results look wrong

Integer division, silent truncation (decimals quietly chopped off) and overflow (a number too big for its type wrapping round to a wrong one) all trace back to an unintended dtype.

np.array([1, 2, 3]).dtype int64 # one float makes the whole array float np.array([1, 2, 3.5]).dtype float64 # one string makes it ALL strings np.array([1, 2, '3']).dtype <U21 # now maths is broken
  • int64whole numbers, each stored in 64 bits (8 bytes)
  • float64decimal numbers (“floats”); one 3.5 turned 1 and 2 into 1.0 and 2.0
  • <U21text (Unicode strings) up to 21 characters: every element is now a string, so + and mean() stop working

Dtype resembles the number format of an Excel column; one word typed into a numeric column turns the whole column into text.

Creating arrays

Creating arrays from ranges, zeros and lists

Arrays are usually built from a range, a count of zeros or evenly spaced points. These four cover most cases. A dimension is one direction of movement: a row of numbers is 1-D; a table with rows and columns is 2-D.

np.zeros(3) # [0. 0. 0.] np.arange(0, 10, 2) # [0 2 4 6 8] np.linspace(0, 1, 5) # [0. .25 .5 .75 1.] np.array([[1, 2], [3, 4]]) # 2-D
  • np.zeros(3)three zeros; 0. is short for 0.0, a float
  • np.arange(0, 10, 2)start at 0, step by 2, stop before 10 (like range)
  • np.linspace(0, 1, 5)5 evenly spaced values from 0 to 1, both ends included
  • np.array([[1, 2], [3, 4]])a list of lists becomes a table: each inner list is one row
Array constructors

Four array-construction functions

Array contents are rarely typed by hand. These four functions cover nearly every case in this course.

linspace vs arange

arange takes a step and may miss the endpoint with floats. linspace takes a count and always includes it. linspace is preferred for plotting.

np.arange(0, 10, 2) [0 2 4 6 8] np.linspace(0, 1, 5) [0. 0.25 0.5 0.75 1. ] np.zeros(3), np.ones((2,2)) [0. 0. 0.] [[1. 1.] [1. 1.]] rng = np.random.default_rng(42) rng.integers(1, 7, size=5) [1 5 4 3 3] # seeded = repeatable
  • np.ones((2,2))the shape goes in as one tuple (2,2), hence the double brackets
  • np.random.default_rng(42)a random-number generator; 42 is the seed: the same seed gives the same numbers every run
  • rng.integers(1, 7, size=5)five whole numbers from 1 to 6 (7 is left out), like five dice rolls
Reshaping

reshape rearranges elements without recomputing them

reshape lays the same elements out in a new shape (rows × columns). The element count must match. Passing -1 for one dimension lets NumPy compute it.

reshape usually returns a view

The write-through behaviour described in Part C therefore applies here too. .copy() gives an independent array.

Key term

view
a new way of looking at the same numbers: change one and the other changes too (Part C shows it)
a = np.arange(12) a.reshape(3, 4) [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] a.reshape(3, -1).shape (3, 4) # -1 = "you figure it out" a.reshape(5, 2) ValueError: cannot reshape array of size 12 into shape (5,2)
  • np.arange(12)the 12 numbers 0 to 11 in one row
  • a.reshape(3, 4)the same 12 numbers as 3 rows × 4 columns, filled row by row
  • a.reshape(3, -1)-1 = “work it out”: 12 ÷ 3 = 4 columns
  • ValueError: cannot reshape…read the last line: 5 × 2 = 10 places, but there are 12 elements
Array attributes

.shape and .dtype describe size and content

The shape is the number of elements along each dimension; the dtype is the type of the content. An array is one type throughout: a single string converts every element to text.

m = np.array([[1, 2, 3], [4, 5, 6]]) m.shape # (2, 3) -> 2 rows, 3 cols m.dtype # int64 m.size # 6 total elements
  • m = np.array([[1, 2, 3], [4, 5, 6]])two inner lists = two rows of three numbers
  • m.shape(2, 3): a tuple, 2 along the first dimension (rows), 3 along the second (columns)
  • m.dtypeint64: every element is a whole number
  • m.size6: total elements, 2 × 3
Review question

Question (select to reveal the answer)

m = np.arange(1, 21).reshape(4, 5) holds the numbers 1 to 20 in 4 rows and 5 columns. What is m.reshape(2, -1).shape?

A · (2, 10)
B · (10, 2)
C · (2, -1)
D · an error

A — (2, 10).

-1 asks NumPy to work out that size: 20 elements in 2 rows leave 10 columns. reshape(3, 7) fails with ValueError: cannot reshape array of size 20 into shape (3,7), because 3 × 7 = 21.

Review question

Question (select to reveal the answer)

small = np.array([100, 120], dtype=np.int8). What does print(small + 50) show?

A · [150 170]
B · [-106 -86]
C · an OverflowError
D · [127 127]

B — [-106 -86].

int8 holds only −128 to 127, so 150 wraps round to 150 − 256 = −106, and 170 to −86. NumPy gives no warning.

Core concept

One operation applied to every element

Loop: one at a time 1 2 3 … step, step, step — slow Vectorized: all at once 1 2 3 … a * 2 — one instruction
Part B

Operations

Maths and summaries across the whole array.

Part A defined the array and its shape and dtype. This part performs maths on it: one operator or method call acts on every element.

Elementwise

Operators apply to every element

Elementwise means “to each element separately”. Adding, multiplying or taking a square root applies the operation to each element and returns a new array, with no loop and no .append().

a = np.array([1, 4, 9]) a * 2 # [ 2 8 18] a + a # [ 2 8 18] np.sqrt(a) # [1. 2. 3.]
  • a * 2every element doubled: [ 2 8 18] (the extra spaces align the numbers)
  • a + atwo arrays of the same shape are added position by position
  • np.sqrt(a)square root of each element; 1. means 1.0, because roots are floats
Exercise · 4 min

Squaring a million numbers with a loop and with NumPy

Both functions square every number. time_ms measures each one.

Tasks

  1. Predict how many times faster NumPy is.
  2. Run the code.
  3. Replace x * x with x ** 0.5 and arr * arr with np.sqrt(arr). Does the gap grow or shrink?

Result on the lecture laptop (select to reveal)

Loop 15.1 ms, NumPy 0.12 ms: about 120×. Square roots give about the same gap (24.4 ms against 0.22 ms). The comprehension creates a million new Python floats; NumPy writes into one block of memory.

# time_ms(f) is the helper from the timeit slide nums = [i * 0.5 for i in range(1_000_000)] arr = np.array(nums) def with_loop(): return [x * x for x in nums] def with_numpy(): return arr * arr print(f"loop : {time_ms(with_loop):.2f} ms") print(f"numpy: {time_ms(with_numpy):.2f} ms")
  • [x * x for x in nums]a comprehension: builds a new list, one square at a time
  • arr * arrelementwise: each element times itself, in one operation
Aggregations

Reducing an array to a single number

Sum, mean, max and standard deviation each reduce the whole array at once. These summaries are called aggregations: many values in, one value out. These summaries are reported for almost every dataset.

temps = np.array([28, 31, 33, 29]) temps.sum() # 121 temps.mean() # 30.25 temps.max() # 33 temps.std() # 1.92
  • temps.sum()all four temperatures added: 121
  • temps.mean()the average: 121 ÷ 4 = 30.25
  • temps.max()the largest value: 33
  • temps.std()standard deviation, the typical distance from the mean: about 1.92 degrees
Worked example

The built-in sum() is a fairer opponent

A hand-written loop is the slowest way to add numbers in Python. The built-in sum() also runs its loop in C, but over Python objects.

Result

sum() is about 5× faster than the loop, and NumPy is still about 11× faster than sum(), because it adds raw numbers rather than Python objects.

# time_ms(f) is the helper from the timeit slide nums = [i * 0.5 for i in range(1_000_000)] arr = np.array(nums) def with_loop(): total = 0.0 for x in nums: total += x return total def with_builtin(): return sum(nums) print(f"for loop : {time_ms(with_loop):.2f} ms") print(f"sum(nums) : {time_ms(with_builtin):.2f} ms") print(f"arr.sum() : {time_ms(arr.sum):.3f} ms") for loop : 6.82 ms sum(nums) : 1.26 ms arr.sum() : 0.113 ms
  • sum(nums)built-in: loops in C, but still unpacks one Python float at a time
  • time_ms(arr.sum)the method without brackets: time_ms calls it
Exercise · 4 min

Mean and standard deviation by hand and with NumPy

The statistics formulas written as Python loops, against two NumPy calls. The answers must match before the speeds mean anything.

Tasks

  1. Check that both lines print the same mean and standard deviation.
  2. Compare the two times.
  3. Change size=100_000 to size=1_000 and run again. What happens to the ratio?

Result on the lecture laptop (select to reveal)

Both give mean 74.9541 and standard deviation 9.9653. By hand 4.86 ms, NumPy 0.066 ms: about 75×. With 1,000 scores the ratio drops to about 10× (0.047 ms against 0.0045 ms), as the size chart predicts.

# time_ms(f) is the helper from the timeit slide rng = np.random.default_rng(1) scores = rng.normal(75, 10, size=100_000) # made-up exam scores data = scores.tolist() # the same numbers as a list def by_hand(): mean = sum(data) / len(data) var = sum((x - mean) ** 2 for x in data) / len(data) return mean, var ** 0.5 def with_numpy(): return scores.mean(), scores.std() m1, s1 = by_hand() m2, s2 = with_numpy() print(f"by hand: mean {m1:.4f}, std {s1:.4f} {time_ms(by_hand):.2f} ms") print(f"numpy : mean {m2:.4f}, std {s2:.4f} {time_ms(with_numpy):.3f} ms")
  • rng.normal(75, 10, size=100_000)made-up, bell-shaped scores centred on 75 with a typical spread of 10
  • scores.tolist()the same numbers as an ordinary list of Python floats
  • sum((x - mean) ** 2 for x in data)squared distance from the mean, added up; divided by the count it is the variance, and ** 0.5 takes its square root
2-D summaries

axis selects the direction to collapse

m = np.array([[1, 2, 3], [4, 5, 6]]) # shape (2, 3): 2 rows, 3 columns m.sum() 1 2 3 4 5 6 21 everything one number m.sum(axis=0) 1 2 3 4 5 6 5 7 9 axis=0: down the rows one total per column · shape (3,) m.sum(axis=1) 1 2 3 4 5 6 6 15 axis=1: across the columns one total per row · shape (2,)
Exercise · 3 min

Averages per student and per quiz with axis

A made-up gradebook: 5 students (rows) by 4 quizzes (columns).

Tasks

  1. Predict the shapes of per_student and per_quiz.
  2. Run the code.
  3. Find the student with the highest average, using .argmax().

Result on the lecture laptop (select to reveal)

per_student has shape (5,), one average per row; per_quiz has shape (4,). Quiz 2 (the third column, counting from 0) is the hardest, at 79.4. per_student.argmax() is 0: the first student, with 91.75.

rng = np.random.default_rng(7) grades = rng.integers(60, 101, size=(5, 4)) # 5 students x 4 quizzes print(grades) per_student = grades.mean(axis=1) per_quiz = grades.mean(axis=0) print("per student:", per_student) print("per quiz: ", per_quiz) print("hardest quiz is number", per_quiz.argmin())
  • rng.integers(60, 101, size=(5, 4))whole numbers from 60 to 100, in a 5 × 4 table
  • per_quiz.argmin()the position of the smallest value; argmax() gives the largest
Broadcasting a scalar

A scalar is stretched to fit the array

Broadcasting lets a single number (a scalar) act on every element without being written out for each one. Adding 12% VAT to a whole price list takes one multiplication.

prices = np.array([100, 200, 300]) prices * 1.12 # [112. 224. 336.] prices - prices.mean() # centred
  • prices * 1.12the one number 1.12 is stretched to [1.12, 1.12, 1.12]: [112. 224. 336.]
  • prices - prices.mean()the mean (200) is subtracted from every price: [-100. 0. 100.] — each price’s distance from average

A teacher announcing “add 5 marks for everyone” gives one instruction that applies to every student, without writing 5 beside each name.

Worked example

Converting a year of temperatures at once

8,760 made-up hourly readings in °C, converted to °F with F = C × 9/5 + 32.

Result

About 45× faster: less than with a million numbers, as the size chart predicts. Converting back is one line as well: (f - 32) * 5 / 9.

# time_ms(f) is the helper from the timeit slide rng = np.random.default_rng(3) celsius = rng.normal(28, 2, size=365 * 24) # a year of hourly readings readings = celsius.tolist() def with_loop(): return [c * 9 / 5 + 32 for c in readings] def with_numpy(): return celsius * 9 / 5 + 32 f = with_numpy() print(f"{f.size} readings, hottest {f.max():.1f} F") print(f"loop : {time_ms(with_loop):.3f} ms") print(f"numpy: {time_ms(with_numpy):.3f} ms") 8760 readings, hottest 96.9 F loop : 0.272 ms numpy: 0.006 ms
  • size=365 * 24days × hours: one reading per hour for a year
  • celsius * 9 / 5 + 32broadcasting: 9, 5 and 32 apply to all 8,760 readings
Review question

Question (select to reveal the answer)

Given a = np.array([1, 2, 3]), what is a * 3?

A · [1, 2, 3, 1, 2, 3, 1, 2, 3]
B · [3, 6, 9]
C · 6
D · an error

B — [3, 6, 9].

On an array, * 3 multiplies every element. On a Python list, * 3 would repeat it (answer A) — a key difference between the two.

Break

  Five minutes

Next: selecting specific values from an array.

Part C

Indexing & selecting

Slice by position, or select by condition.

Week 3 sliced lists with nums[1:3]. This part applies the same brackets to arrays, with one index per dimension, and adds selection by condition.

By position

Slicing works in each dimension

One index per axis, separated by a comma. A lone : means "all of this axis", so m[:, 0] is the whole first column.

a = np.array([10, 20, 30, 40]) a[1:3] # [20 30] m = np.array([[1, 2], [3, 4]]) m[0, 1] # 2 (row 0, col 1) m[:, 0] # [1 3] first column
  • a[1:3]positions 1 and 2 (a slice stops before the end number): [20 30]
  • m[0, 1]row 0, column 1 — counting from 0, like list positions: 2
  • m[:, 0]: = every row; 0 = column 0: [1 3]
By condition

Selecting elements with a boolean mask

temps four temperatures temps > 30 the mask: True where above 30 temps[temps > 30] kept: the True positions 28 False 31 True 33 True 29 False 31 33
Exercise · 4 min

Counting sixes in a million dice rolls

A loop with an if counts the sixes one at a time; a mask counts them in one expression.

Tasks

  1. Predict roughly how many of a million rolls are sixes.
  2. Run the code.
  3. Change the mask to count rolls of 5 or more: (rolls >= 5).sum().

Result on the lecture laptop (select to reveal)

166,872 sixes, close to 1,000,000 ÷ 6 ≈ 166,667. Loop 7.70 ms, mask 0.222 ms: about 35×. Rolls of 5 or more: 334,116, about a third.

# time_ms(f) is the helper from the timeit slide rng = np.random.default_rng(0) rolls = rng.integers(1, 7, size=1_000_000) # a million dice rolls roll_list = rolls.tolist() def with_loop(): count = 0 for r in roll_list: if r == 6: count += 1 return count def with_mask(): return (rolls == 6).sum() print(with_loop(), with_mask()) print(f"loop: {time_ms(with_loop):.2f} ms mask: {time_ms(with_mask):.3f} ms")
  • rolls.tolist()the same rolls as a list, for the loop
  • (rolls == 6).sum()a mask of True/False, summed: each True counts as 1
Common error

A slice is not a copy

It is a window onto the same memory. Writing through it changes the original.

Views

a[1:4] returns a view, not a copy

Slicing an array does not copy the data. The result is a view (a window onto the same numbers), and assigning into it changes the original array.

Reason for this design

Copying a large array is expensive. A view costs nothing, which makes chained slicing cheap. The cost is this write-through behaviour.

a = np.array([1,2,3,4,5]) s = a[1:4] # a VIEW s[0] = 999 print(a) [ 1 999 3 4 5] # you never touched `a` by name s.base is a True # the giveaway
  • s = a[1:4]s is a view: a window onto positions 1–3 of a
  • s[0] = 999write into the window…
  • print(a)…and a[1] changed too: [ 1 999 3 4 5]
  • s.base is a.base = the array a view looks through; True means s is a view of a
Copies

Fancy indexing returns a copy

Fancy indexing means indexing with a list of positions instead of a slice. NumPy builds a new array, so the original is unaffected.

Guideline

Slice a[1:4] → view. List a[[1,2,3]] or mask a[a>2] → copy. When unsure, call .copy() explicitly.

a = np.array([1,2,3,4,5]) f = a[[1,2,3]] # a COPY f[0] = 999 print(a) [1 2 3 4 5] # unchanged f.base is None True
  • f = a[[1,2,3]]outer brackets index, inner brackets are a list of positions: a new array (a copy)
  • print(a)changing f left a alone: [1 2 3 4 5]
  • f.base is NoneNone = “no base”: f owns its own numbers
Worked example

A view costs almost nothing; a copy costs time

A slice is a view, so no numbers are copied. .copy() duplicates them.

Result

The copy takes about 2,000 times as long as the view. With ten times the data the copy takes ten times as long (1,241 µs); the view does not change, because it copies nothing.

# time_ms(f) is the helper from the timeit slide a = np.arange(1_000_000, dtype=float) def take_view(): return a[::2] # every second element def take_copy(): return a[::2].copy() print("the view shares a's memory:", take_view().base is a) print(f"view: {time_ms(take_view) * 1000:8.2f} microseconds") print(f"copy: {time_ms(take_copy) * 1000:8.2f} microseconds") the view shares a's memory: True view: 0.06 microseconds copy: 118.46 microseconds
  • a[::2]every second element (a step of 2), as a view
  • time_ms(take_view) * 1000milliseconds to microseconds (µs, millionths of a second)
Broadcasting

A smaller shape stretches when the trailing sizes are compatible

Works np.ones((3, 4)) + np.array([1, 2, 3, 4]) 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. + 1 2 3 4 1 2 3 4 1 2 3 4 = 2. 3. 4. 5. 2. 3. 4. 5. 2. 3. 4. 5. stretched to 3 rows shape (3, 4) (3, 4) and (4,) last sizes 4 and 4 match ✓ the row of 4 is added to all 3 rows Fails np.ones((3, 4)) + np.array([1, 2, 3]) 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. + 1 2 3 ? (3, 4) and (3,) last sizes 4 and 3 differ ✗ neither is 1, so NumPy cannot stretch the row ValueError: operands could not be broadcast together with shapes (3,4) (3,)
Exercise · 3 min

Centring every column with broadcasting

Subtracting each column’s mean shifts every column to an average of zero, a common step before modelling.

Tasks

  1. Predict the three shapes printed on the first line.
  2. Run the code and check the last line.
  3. Try m - m.mean(axis=1) and read the error. Why do the shapes not line up?

Result on the lecture laptop (select to reveal)

(4, 3) (3,) (4, 3), and every column sums to 0. m.mean(axis=1) has shape (4,); the trailing sizes 3 and 4 differ, so broadcasting fails: operands could not be broadcast together with shapes (4,3) (4,).

rng = np.random.default_rng(5) m = rng.integers(0, 100, size=(4, 3)) # 4 rows, 3 columns col_means = m.mean(axis=0) # shape (3,) centred = m - col_means # (4, 3) minus (3,) print(m.shape, col_means.shape, centred.shape) print(centred) print(centred.sum(axis=0)) # each column now sums to 0
  • m - col_meansthe 3 column means are stretched down all 4 rows
  • centred.sum(axis=0)one total per column: all zero once centred
Vectorised if/else

np.where as a vectorised if/else

Three arguments: a condition, a value where it is true, a value where it is false. It returns a new array.

Use in data cleaning

Datasets often use a placeholder such as -999 to mean “no reading”. np.where(x == -999, np.nan, x) marks every one as missing in one line.

Key term

NaN / np.nan
“Not a Number”: NumPy’s marker for a missing value. Sums and means that include it give NaN, so it remains visible
x = np.array([10, -5, 3, -8]) np.where(x < 0, 0, x) [10 0 3 0] # condition, if-true, if-false # no loop, no append, no index
  • x < 0the condition, checked for every element: [F T F T]
  • np.where(x < 0, 0, x)where it is True use 0, otherwise keep x: [10 0 3 0]
Exercise · 4 min

Replacing placeholder values with np.where

Five per cent of these made-up readings are −999, a placeholder meaning “no reading”.

Tasks

  1. Run the code and note how many readings are missing.
  2. Add print(x.mean()), the mean with the −999s left in. How wrong is it?
  3. Compare the two times.

Result on the lecture laptop (select to reveal)

50,039 missing; the clean mean is 30.00. With the placeholders left in, x.mean() is −21.49: one unnoticed placeholder ruins the average. Loop 12.55 ms, np.where 0.43 ms: about 30×.

# time_ms(f) is the helper from the timeit slide rng = np.random.default_rng(9) x = rng.normal(30, 3, size=1_000_000) # made-up temperatures x[rng.random(x.size) < 0.05] = -999 # 5% marked "no reading" data = x.tolist() def with_loop(): return [float("nan") if v == -999 else v for v in data] def with_where(): return np.where(x == -999, np.nan, x) clean = with_where() print(f"{np.isnan(clean).sum()} missing; mean of the rest {np.nanmean(clean):.2f}") print(f"loop: {time_ms(with_loop):.2f} ms np.where: {time_ms(with_where):.2f} ms")
  • x[rng.random(x.size) < 0.05] = -999assignment through a mask: about 5% of the positions get −999
  • np.isnan(clean).sum()a mask of the NaNs, summed: how many are missing
  • np.nanmean(clean)the mean, skipping NaN values
Performance

np.append in a loop is slower than a list

An array is a fixed block of memory. There is no room at the end, so every np.append allocates (reserves) a whole new array and copies everything across.

Reading the comments

O(n^2)
shorthand for “work grows with the square of the size”: 10× more data, about 100× more time
O(n)
work grows in step with the size: 10× more data, 10× more time

Alternative

Build a Python list and convert once, or allocate with np.zeros(n) and fill by index. An array should not be grown inside a loop.

# time_ms(f) is the helper from the timeit slide def grow(): # O(n^2) out = np.array([]) for i in range(10000): out = np.append(out, i) return out def build_list(): # O(n) return np.array([i for i in range(10000)]) def direct(): return np.arange(10000) print(f"np.append : {time_ms(grow):.2f} ms") print(f"list, then : {time_ms(build_list):.3f} ms") print(f"np.arange : {time_ms(direct):.4f} ms") np.append : 14.02 ms list, then : 0.229 ms np.arange : 0.0014 ms
  • out = np.append(out, i)each pass builds a brand-new array one element longer: 10,000 copies
  • np.array([i for i in range(10000)])a comprehension (week 4) grows a list cheaply; then one conversion to an array: about 60× faster
  • np.arange(10000)fastest: NumPy creates the numbers directly, 10,000× faster than np.append
Shape errors

Three common shape errors and their meaning

Exercise · 8 min

Views, axes and broadcasting errors

1 · Demonstrate a view

Make a = np.arange(10). Slice b = a[2:5]. Set b[0] = -1. Print a. Explain what happened.

2 · Prevent the change

Repeat step 1 so that a is unchanged. Find two ways.

3 · Sum along each axis

Build a 3×4 array. Produce one total per column, then one per row. Check that the shapes are as expected.

4 · Trigger a broadcasting error

Add an array whose shape cannot broadcast. Read the error, which names both shapes.

Synthesis

Summarising rainfall data

Filtering the wet days, averaging them and counting the dry days takes three one-line expressions and no loop.

rain = np.array([0, 12, 4, 33, 0, 8]) wet = rain[rain > 0] wet.mean() # 14.25 mm (rain == 0).sum() # 2 dry days
  • wet = rain[rain > 0]mask: keep the days with some rain, [12 4 33 8]
  • wet.mean()(12 + 4 + 33 + 8) ÷ 4 = 14.25 mm on an average wet day
  • (rain == 0).sum()True counts as 1 and False as 0, so summing the mask counts the dry days: 2
Core concept

The share of darts inside the quarter circle estimates π

0 1 1 100 darts: 84 inside π ≈ 4 × 84 / 100 = 3.36 0 1 1 1,000 darts: 787 inside π ≈ 4 × 787 / 1,000 = 3.148
Exercise · 5 min

Estimating π by throwing random darts

Random points in a 1 × 1 square land inside the quarter circle x² + y² ≤ 1 with probability π/4, so four times the fraction inside estimates π. The NumPy version uses almost everything from this week.

Tasks

  1. Run the code and compare the two estimates.
  2. Change n to 1_000, then to 3_000_000. How does the estimate change?
  3. Which operations from this week does with_numpy use?

Result on the lecture laptop (select to reveal)

Both give 3.142436, because they use the same darts. Loop 68 ms, NumPy 0.9 ms: about 75×. 1,000 darts give 3.148; 3,000,000 give 3.1407: more darts, closer estimate. with_numpy uses elementwise maths, a comparison mask and a mean.

# time_ms(f) is the helper from the timeit slide rng = np.random.default_rng(42) n = 1_000_000 x, y = rng.random(n), rng.random(n) # n darts in a 1 x 1 square xs, ys = x.tolist(), y.tolist() def with_numpy(): inside = x**2 + y**2 <= 1 # inside the quarter circle? return 4 * inside.mean() def with_loop(): hits = 0 for i in range(n): if xs[i]**2 + ys[i]**2 <= 1: hits += 1 return 4 * hits / n print(with_numpy(), with_loop()) print(f"loop: {time_ms(with_loop):.0f} ms numpy: {time_ms(with_numpy):.1f} ms")
  • rng.random(n)n random decimals between 0 and 1
  • x**2 + y**2 <= 1a mask: True where the dart is inside the quarter circle
  • 4 * inside.mean()the mean of a mask is the fraction of Trues
Case study

34,079 flood control budgets

The same array operations, on a real public dataset: the government’s (DPWH) list of flood control projects, which DS 227, the companion course, is cleaning this week.

Loading the data

From CSV to a NumPy array

Each summary on the following slides is one call on this array, without loops.

Checking shape and dtype first

They confirm that the load worked before any later number is trusted.

import csv, io, requests url = "https://portal.latarak.com/api/flood/export.csv" resp = requests.get(url, timeout=60) rows = list(csv.DictReader(io.StringIO(resp.text))) budgets = np.array([float(r["budget"]) for r in rows]) budgets.shape, budgets.dtype ((34079,), dtype('float64')) budgets.sum() 1600088782392.83 # PHP 1.6 trillion
  • requests.get(url)downloads the whole dataset from the course API in one request; week 9 covers requests properly
  • io.StringIO(resp.text)makes the downloaded text behave like an open file, so csv.DictReader reads it exactly as in week 3
  • float(r["budget"]) for r in rowstake each row’s budget text and make it a float
  • ((34079,), dtype('float64'))1-D, 34,079 elements, all decimals — the load worked
  • 1600088782392.83the grand total in pesos: about 1.6 trillion (1,600,088,782,392.83)
Summary statistics

Four summaries in four lines, without a loop

budgets.mean() 46,952,340 np.median(budgets) 37,676,233 # mean > median => right skew
budgets.max() 1,447,499,996 (budgets > 1e9).sum() 3 # over PHP 1B # a bool array sums as 0/1
Masks on the budget data

Select rows by a condition, not a position

A boolean array used as an index keeps exactly the elements where it is True. This is the most frequently used selection technique.

Masks compose

Combine with & and | — and keep the parentheses, because & binds tighter than >.

big = budgets[budgets > 1e9] np.sort(big)[::-1] array([1.44750000e+09, 1.09625523e+09, 1.04278280e+09]) # mid-size band: note the () mid = budgets[(budgets > 1e8) & (budgets < 5e8)] mid.size 2145
  • np.sort(big)[::-1]sort smallest-first, then [::-1] reverses it: biggest first
  • 1.44750000e+09scientific notation: 1.4475 × 109, about 1.45 billion pesos
  • (budgets > 1e8) & (budgets < 5e8)& = “and” for masks: between 100 million and 500 million
  • mid.sizehow many elements passed both tests: 2145 projects
Ranking

argsort returns positions, not values

argsort returns the positions that would put the array in order. Finding "the top ten projects", rather than "the top ten numbers", requires the indices, which are then used to look up the other columns.

Common pattern

order = arr.argsort()[::-1] then [rows[i] for i in order[:10]]. One sort supports any later lookup.

order = budgets.argsort()[::-1] order[:3] array([18777, 33185, 28049]) # POSITIONS of the 3 biggest # now look up the real records for i in order[:3]: print(rows[i]["region"]) Central Office Central Office Central Office
  • budgets.argsort()[::-1]positions from smallest to biggest, reversed: biggest first
  • order[:3]the first three positions: where the three biggest budgets sit
  • rows[i]["region"]use each position to look up that project’s other columns in rows
Concentration

The top 1% of projects hold 6.5% of all spending

SliceProjectsShare of ₱1.6T
Top 1%3416.5%
Over ₱1 billion30.2%
Below the median17,03916.5%
Review question

Question (select to reveal the answer)

After b = a[0:3] and then b[:] = 0, what happens to a?

A · Nothing — b is a separate copy
B · Its first three elements become 0, because a slice is a view
C · It raises a ValueError about read-only arrays
D · Only b changes, unless .flush() is called
B. Basic slicing returns a view that shares memory with the original, so writing through it changes a. Check with b.base is a → True. Use a[0:3].copy() for an independent array.
Review question

Question (select to reveal the answer)

m has shape (2, 3). What shape does m.sum(axis=0) return?

A · (2,) — one total per row
B · (3,) — one total per column
C · (2, 3) — unchanged
D · a single number
B. The named axis is the one that disappears. Naming axis 0 collapses the 2 rows, leaving one total per column — shape (3,). axis=0 goes down, axis=1 goes across.
Significance

NumPy as the foundation for later tools

Review question

Question (select to reveal the answer)

For a = np.array([5, 12, 7, 20]), what does a[a > 10] return?

A · [True, True]
B · [12, 20]
C · [5, 7]
D · 2

B — [12, 20].

a > 10 is the mask [F T F T]; indexing with it keeps the elements where it is True. To count them instead, use (a > 10).sum().

This week's lab

Arrays, summaries, and a mask

The lab covers building arrays, elementwise maths, axis-wise summaries of a 2-D array, and filtering real weather data with a boolean mask. ~45 minutes.

Lab tasks

np.array, arange, aggregations, axis=, and a[a > k].

Optional extension

Time a loop against its vectorised version with time_ms() from the slides, or with %timeit (a notebook command that times one line).

Summary

Arrays, operations and indexing: summary

Glossary

Terms introduced this week

The array

array (ndarray)
NumPy’s container: many values of one type, side by side
element
one value inside an array
dtype
the one type all elements share: int64, float64, <U21 (text)
dimension
one direction to move in: 1-D row, 2-D table
shape
elements per dimension, e.g. (2, 3) = 2 rows, 3 columns
pointer / byte
a note saying where a value lives / a small unit of memory
C code
fast, pre-translated code that NumPy runs internally
reshape
lay the same elements out in a new shape
seed
a starting number that makes “random” numbers repeatable

Maths and selecting

vectorised operation
one line of maths applied to every element, no Python loop
elementwise
done to each element separately, position by position
aggregation
many values in, one out: sum, mean, max, std
axis
which dimension to collapse: 0 down the rows, 1 across
broadcasting
stretching a smaller array or number to fit a bigger one
boolean mask
True/False per element; a[mask] keeps the True ones
view / copy
a window onto the same numbers / an independent duplicate
fancy indexing
indexing with a list of positions; always makes a copy
np.where
vectorised if/else: condition, value-if-true, value-if-false
NaN
“Not a Number”: the marker for a missing value
argsort
the positions that would sort an array
benchmark
timing two versions of the same task; the answers must match first
perf_counter / timeit
a clock for durations / a module that repeats a call and times it
Preparation for next week

Practice & reading

Next Week

Data manipulation with pandas I

The DataFrame, a spreadsheet controlled with code: loading a CSV, then selecting and filtering rows and columns.

DS 208 · Programming for Data Science