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
The ndarray: many numbers of one type, stored side by side.
Maths and summaries on the whole array, without a loop.
Slice, and select by condition with a boolean mask.
NumPy underlies pandas, scikit-learn (a machine-learning library) and most other Python data tools.
Replace a slow Python loop with a single, readable NumPy expression.
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.
List and loop: many lines, and slow on realistic dataset sizes.
Array and one operation: shorter, clearer and often 50× faster.
Jim Hugunin writes Python’s first array library.
A rewrite, built to handle Hubble Space Telescope images.
Travis Oliphant merges the two; NumPy 1.0 is released in 2006.
The first major version in 18 years.
NumPy kept the best of both: Numarray’s features and Numeric’s speed on small arrays.
A library is code someone else wrote that a program loads with import. NumPy is one library; Numeric and Numarray were two older ones it replaced.
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
downloads in September 2026 alone: about 300 every second.
Part of the software behind the first black-hole image (2019) and the discovery of gravitational waves (2016).
Open source: anyone may read, use and change the code. Volunteers and sponsored developers maintain it.
pandas, scikit-learn and matplotlib are built on NumPy arrays, so this week’s skills carry into every later week.
pip install numpy, by a person or by an automated serverSourceDownloads: pypistats.org, without mirrors, retrieved 11 Oct 2026; science uses: Harris et al., Nature 585 (2020); governance: numpy.org/about
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])
One value inside an array — like one cell of a spreadsheet.
e.g. in [10, 20, 30], 20 is the element at position 1
The data type every element shares: whole numbers, decimals, text…
e.g. int64 (whole numbers), float64 (decimals)
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
How many elements along each dimension, written as a tuple (rows, columns).
e.g. (2, 3) = 2 rows, 3 columns
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
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
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]
An array of True/False, one per element, used to keep only the True ones.
e.g. temps[temps > 30] keeps the hot days
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.
The first run downloads Python and NumPy into the page, which takes about ten seconds. Later runs start at once.
int32 where the slides show int64Printed 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.
np.__version__the installed NumPy version: 2.5.3 on the laptop, 1.26.4 in the browsersys.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 int32Many 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.
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 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 containerarray([1, 2, 3])how a notebook shows an array; the word array indicates that it is not a listA Python list holds pointers (notes saying where each value really lives) to objects scattered across memory. An array holds the numbers themselves, side by side, all the same type.
A list is a coat-check rack of tickets that point to coats stored elsewhere; an array is an egg tray, with each value next to the last, so NumPy reads the whole block at once.
Because every element is an 8-byte float, NumPy passes the whole block to optimised C code, with no per-element type check or pointer lookup.
float64 number takes 8 bytesThe previous slide states that a list of a million floats needs about four times the memory of the array. sys.getsizeof measures it.
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.
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 pointerssum(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)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 millisecondsnumpy: 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 measurementTiming two versions of the same task is a benchmark. Both must give the same answer first: here both totals are 249999750000.0.
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.
time_ms(f) returns the average milliseconds per call of f. Every timed exercise in this deck uses it.
timeit chooses the number of calls itself (1, 2, 5, 10, 20…) until they take at least 0.2 seconds in totalTiming one lap of a running track with a hand stopwatch is unreliable; timing twenty laps and dividing by twenty is not.
timeit.Timer(f).autorange()calls f repeatedly and returns two values: how many calls, and the total seconds they tookseconds / calls * 1000the average for one call, in millisecondstime_ms(big.sum)no brackets after sum: the method itself is handed over, and time_ms calls itMeasured on the lecture laptop with timeit, best of 7 repeats; Python 3.12, NumPy 2.5. µs = microsecond, a millionth of a second.
Every NumPy call has a fixed cost of about 0.2 µs before any adding starts. With 10 numbers that cost dominates and the plain loop wins; from about a thousand numbers NumPy is far ahead, and the ratio settles near 60×.
The claim “NumPy is faster” holds for arrays of realistic size, not for a handful of values. Measuring settles it; assuming does not.
The built-in sum() is 5× faster than the hand-written loop, and NumPy is still about 11× faster than sum() on large arrays.
This compares Python’s built-in sum() with arr.sum() at four sizes. A ratio below 1 means NumPy is slower.
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.
for n in [10, 100, 10_000, 1_000_000]:repeat the whole experiment once for each sizedef 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 commasAn 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.
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.
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 workingDtype resembles the number format of an Excel column; one word typed into a numeric column turns the whole column into text.
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)three zeros; 0. is short for 0.0, a floatnp.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 includednp.array([[1, 2], [3, 4]])a list of lists becomes a table: each inner list is one rowArray contents are rarely typed by hand. These four functions cover nearly every case in this course.
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.ones((2,2))the shape goes in as one tuple (2,2), hence the double bracketsnp.random.default_rng(42)a random-number generator; 42 is the seed: the same seed gives the same numbers every runrng.integers(1, 7, size=5)five whole numbers from 1 to 6 (7 is left out), like five dice rollsreshape 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.
The write-through behaviour described in Part C therefore applies here too. .copy() gives an independent array.
np.arange(12)the 12 numbers 0 to 11 in one rowa.reshape(3, 4)the same 12 numbers as 3 rows × 4 columns, filled row by rowa.reshape(3, -1)-1 = “work it out”: 12 ÷ 3 = 4 columnsValueError: cannot reshape…read the last line: 5 × 2 = 10 places, but there are 12 elements.shape and .dtype describe size and contentThe 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]])two inner lists = two rows of three numbersm.shape(2, 3): a tuple, 2 along the first dimension (rows), 3 along the second (columns)m.dtypeint64: every element is a whole numberm.size6: total elements, 2 × 3m = 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?
(2, 10)(10, 2)(2, -1)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.
A reshape keeps every element and changes only the rows and columns, so the new shape must multiply to the same size.
m.size is 20 and m.sum() is 210 whatever the shape: reshaping recomputes nothing.
small = np.array([100, 120], dtype=np.int8). What does print(small + 50) show?
[150 170][-106 -86]OverflowError[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.
A dtype fixes the range of values an array can hold: int8 covers −128 to 127.
[1, 2, 3] → int64; [1, 2, 3.0] → float64; [1, 2, "3"] → text, <U21; [True, 2] → int64. The browser shows int32 and <U11.
a * 2 instructs NumPy to double every element in optimised C; no Python loop runs. This is vectorization (also spelled vectorisation).
A loop is a cashier scanning items one at a time, whereas a vectorised operation weighs the whole basket in one step.
The loop runs once, in C, over tightly packed memory rather than in Python.
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 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 * 2every element doubled: [ 2 8 18] (the extra spaces align the numbers)a + atwo arrays of the same shape are added position by positionnp.sqrt(a)square root of each element; 1. means 1.0, because roots are floatsBoth functions square every number. time_ms measures each one.
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.
[x * x for x in nums]a comprehension: builds a new list, one square at a timearr * arrelementwise: each element times itself, in one operationSum, 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.sum()all four temperatures added: 121temps.mean()the average: 121 ÷ 4 = 30.25temps.max()the largest value: 33temps.std()standard deviation, the typical distance from the mean: about 1.92 degreesA 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.
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.
sum(nums)built-in: loops in C, but still unpacks one Python float at a timetime_ms(arr.sum)the method without brackets: time_ms calls itThe statistics formulas written as Python loops, against two NumPy calls. The answers must match before the speeds mean anything.
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.
rng.normal(75, 10, size=100_000)made-up, bell-shaped scores centred on 75 with a typical spread of 10scores.tolist()the same numbers as an ordinary list of Python floatssum((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 rootaxis selects the direction to collapseAn axis is a dimension named by number: axis 0 = rows (down), axis 1 = columns (across).
The named axis is the one that disappears: axis=0 removes the row
dimension, leaving a per-column result. The same idea returns in pandas.
In a spreadsheet, axis=0 gives a “Total” row under the columns, and axis=1 a “Total” column to the right of the rows.
A made-up gradebook: 5 students (rows) by 4 quizzes (columns).
per_student and per_quiz..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.integers(60, 101, size=(5, 4))whole numbers from 60 to 100, in a 5 × 4 tableper_quiz.argmin()the position of the smallest value; argmax() gives the largestBroadcasting 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 * 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 averageA teacher announcing “add 5 marks for everyone” gives one instruction that applies to every student, without writing 5 beside each name.
8,760 made-up hourly readings in °C, converted to °F with F = C × 9/5 + 32.
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.
size=365 * 24days × hours: one reading per hour for a yearcelsius * 9 / 5 + 32broadcasting: 9, 5 and 32 apply to all 8,760 readingsGiven a = np.array([1, 2, 3]), what
is a * 3?
[1, 2, 3, 1, 2, 3, 1, 2, 3][3, 6, 9]6B — [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.
Array maths is elementwise; list * is repetition, so the object type determines the result.
Array * n scales; list * n repeats.
Next: selecting specific values from an array.
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.
One index per axis, separated by a comma. A lone : means "all of
this axis", so m[:, 0] is the whole 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: 2m[:, 0]: = every row; 0 = column 0: [1 3]A comparison returns an array of True/False (booleans) — a
boolean mask. Indexing with it keeps only the elements where it is True. This is filtering.
A mask is a stencil laid over the array; the holes (True) let values through and the solid parts (False) block them.
A loop with an if counts the sixes one at a time; a mask counts them in one expression.
(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.
rolls.tolist()the same rolls as a list, for the loop(rolls == 6).sum()a mask of True/False, summed: each True counts as 1It is a window onto the same memory. Writing through it changes the original.
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.
Copying a large array is expensive. A view costs nothing, which makes chained slicing cheap. The cost is this write-through behaviour.
s = a[1:4]s is a view: a window onto positions 1–3 of as[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 aFancy indexing means indexing with a list of positions instead of a slice. NumPy builds a new array, so the original is unaffected.
Slice a[1:4] → view. List a[[1,2,3]] or mask a[a>2] → copy. When unsure, call .copy() explicitly.
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 numbersA slice is a view, so no numbers are copied. .copy() duplicates them.
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.
a[::2]every second element (a step of 2), as a viewtime_ms(take_view) * 1000milliseconds to microseconds (µs, millionths of a second)NumPy compares shapes from the right. Each pair must be equal, or one of them must be 1. The “trailing” size is the last number in each shape.
Read its last line: the error type, then the two shapes that could not be lined up (“operands” = the two arrays on either side of +). Nearly every shape bug is solved by printing .shape on both sides before the operation.
Subtracting each column’s mean shifts every column to an average of zero, a common step before modelling.
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,).
m - col_meansthe 3 column means are stretched down all 4 rowscentred.sum(axis=0)one total per column: all zero once centredThree arguments: a condition, a value where it is true, a value where it is false. It returns a new array.
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.
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]Five per cent of these made-up readings are −999, a placeholder meaning “no reading”.
print(x.mean()), the mean with the −999s left in. How wrong is it?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×.
x[rng.random(x.size) < 0.05] = -999assignment through a mask: about 5% of the positions get −999np.isnan(clean).sum()a mask of the NaNs, summed: how many are missingnp.nanmean(clean)the mean, skipping NaN valuesAn 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.
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.
out = np.append(out, i)each pass builds a brand-new array one element longer: 10,000 copiesnp.array([i for i in range(10000)])a comprehension (week 4) grows a list cheaply; then one conversion to an array: about 60× fasternp.arange(10000)fastest: NumPy creates the numbers directly, 10,000× faster than np.appendcould not be broadcast togetherThe trailing dimensions do not match and neither is 1. Printing both .shapes identifies the mismatch.
cannot reshape array of size 12The element count changed. reshape never adds or discards elements; check whether a filter was intended first.
too many indices for arraya[i, j] was used on a 1-D array, which has one axis and so takes one index.
NumPy’s error messages name the shapes involved. Guideline: read the last line before changing any code.
ValueError (impossible shape); the third is an IndexError (a position that does not exist).shape of each array used on itMake a = np.arange(10). Slice b = a[2:5]. Set b[0] = -1. Print a. Explain what happened.
Repeat step 1 so that a is unchanged. Find two ways.
Build a 3×4 array. Produce one total per column, then one per row. Check that the shapes are as expected.
Add an array whose shape cannot broadcast. Read the error, which names both shapes.
If step 1 does not change a, fancy indexing was used by mistake.
Filtering the wet days, averaging them and counting the dry days takes three one-line expressions and no loop.
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: 2Each dot is one dart: a random (x, y) in the 1 × 1 square. Cyan darts satisfy x² + y² ≤ 1. The quarter circle covers π/4 of the square, so about π/4 of the darts land inside.
Scatter rice over a square tile with a quarter circle drawn on it: the share of grains inside the curve measures the curve’s area.
These are exactly the darts the next slide’s code throws with seed 42 and n = 100 or n = 1_000.
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.
n to 1_000, then to 3_000_000. How does the estimate change?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.
rng.random(n)n random decimals between 0 and 1x**2 + y**2 <= 1a mask: True where the dart is inside the quarter circle4 * inside.mean()the mean of a mask is the fraction of TruesThe 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.
Each summary on the following slides is one call on this array, without loops.
They confirm that the load worked before any later number is trusted.
requests.get(url)downloads the whole dataset from the course API in one request; week 9 covers requests properlyio.StringIO(resp.text)makes the downloaded text behave like an open file, so csv.DictReader reads it exactly as in week 3float(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 worked1600088782392.83the grand total in pesos: about 1.6 trillion (1,600,088,782,392.83)A comparison gives an array of True/False, and summing it counts the trues.
A boolean array used as an index keeps exactly the elements where it is True. This is the most frequently used selection technique.
Combine with & and | — and keep the parentheses, because & binds tighter than >.
np.sort(big)[::-1]sort smallest-first, then [::-1] reverses it: biggest first1.44750000e+09scientific notation: 1.4475 × 109, about 1.45 billion pesos(budgets > 1e8) & (budgets < 5e8)& = “and” for masks: between 100 million and 500 millionmid.sizehow many elements passed both tests: 2145 projectsargsort 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.
order = arr.argsort()[::-1] then [rows[i] for i in order[:10]]. One sort supports any later lookup.
budgets.argsort()[::-1]positions from smallest to biggest, reversed: biggest firstorder[:3]the first three positions: where the three biggest budgets sitrows[i]["region"]use each position to look up that project’s other columns in rows| Slice | Projects | Share of ₱1.6T |
|---|---|---|
| Top 1% | 341 | 6.5% |
| Over ₱1 billion | 3 | 0.2% |
| Below the median | 17,039 | 16.5% |
Three lines of NumPy answer a question about the concentration of public spending. Once the data is in an array, the analysis itself is short.
np.sort(budgets)[::-1][:341].sum() / budgets.sum() — sort biggest-first, keep the first 341 (1% of 34,079), add them up, divide by the grand total.
After b = a[0:3] and then b[:] = 0, what happens to a?
b is a separate copyb changes, unless .flush() is calleda. Check with b.base is a → True. Use a[0:3].copy() for an independent array.m has shape (2, 3). What shape does m.sum(axis=0) return?
(2,) — one total per row(3,) — one total per column(2, 3) — unchanged(3,). axis=0 goes down, axis=1 goes across.Bulk operations in C, often tens of times faster than a Python loop.
rain[rain > 0] reads like the question being asked.
pandas columns are arrays; scikit-learn (a machine-learning library) takes arrays as input.
Next week's pandas Series is a labelled NumPy array, so the same maths applies directly.
DataFrames are filtered with masks in the same way.
For a = np.array([5, 12, 7, 20]),
what does a[a > 10] return?
[True, True][12, 20][5, 7]2B — [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().
Mask to keep values; .sum() the mask to count
them.
a[mask] selects; mask.sum() counts.
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.
np.array, arange, aggregations, axis=, and
a[a > k].
Time a loop against its vectorised version with time_ms() from the slides, or with %timeit (a notebook command that times one line).
One type, stored side by side. Check .shape and .dtype.
Elementwise maths and axis-wise summaries, without loops.
Slice by position; select by condition with a boolean mask.
In summary: once the numbers are in an array, one expression describes the computation and NumPy runs the loop in fast C code.
Computation over whole datasets in single, readable lines.
int64, float64, <U21 (text)(2, 3) = 2 rows, 3 columnssum, mean, max, std0 down the rows, 1 acrossa[mask] keeps the True onesFinish the Week 5 lab and submit it. The boolean-mask section should be reproducible from memory.
NumPy "Absolute Beginners" guide — numpy.org/doc/stable/user/absolute_beginners. On timing code: pythonprogramming.net, “Timeit Module” (Intermediate Python, part 6) — pythonprogramming.net/timeit-intermediate-python-tutorial.
Everything here is linked on the course page beside this deck.
pandas adds column names and an index to these arrays.
The DataFrame, a spreadsheet controlled with code: loading a CSV, then selecting and filtering rows and columns.
DS 208 · Programming for Data Science