NumPy for Data Analysis
Every chapter so far has processed data one Python value at a time — a for loop touching one list item per iteration. NumPy introduces a genuinely different way of thinking: instead of writing a loop that says "do this to each item," you write one expression that says "do this to the whole array at once," and a highly optimized C library underneath handles the looping for you, dramatically faster and in far less code. This is the first data-science-flavored chapter in the course — NumPy is the foundation nearly every other Python data tool (pandas, scikit-learn, TensorFlow, PyTorch) is built on top of.
How to read this chapter
- Sub-topic 1 makes the case for arrays over lists with a concrete before/after — read it even if you're impatient to get to the syntax, since everything after it assumes you've seen why this trade is worth making.
- Sub-topics 2-3 cover the mechanics: creating arrays and reading them back out with indexing, slicing, and boolean masking — sub-topic 3's masking idiom is the single most important habit to walk away with.
- Sub-topics 4-5 cover vectorized math, broadcasting, and the aggregate functions (
.sum(),.mean(), etc.) with theaxis=parameter, which trips up nearly everyone the first time. - Sub-topic 6 covers reshaping arrays and stacking them together.
- NumPy must be installed to run these examples locally (
pip install numpy) — every graded example in this course (quiz, exercises, practice, challenges) runs it for you already, in-browser via Pyodide.
for loop adding up every grade in a list, one at a time, to compute a class average. That pattern works fine for a handful of numbers. Now picture a sensor logging a measurement every second for a full day (86,400 readings), or a spreadsheet of exam scores across 40 students and 6 subjects. The loop still "works" — it's just slow, verbose, and gets harder to read the moment you need a 2D grid instead of a flat list. NumPy exists to make exactly this kind of numeric work fast and short.
1. What NumPy is, and why it exists
- NumPy ("Numerical Python") provides the
ndarray— a fixed-type, fixed-size array — plus fast, vectorized operations on it. - A Python
listis flexible (mixed types, easy to grow) but slow for numeric math, since every arithmetic operation on it runs as a Python-level loop under the hood. - A NumPy array stores numbers in one contiguous, single-type block of memory and runs operations on the whole array in optimized C code — often 10-100x faster than the equivalent Python loop.
ndarray ("n-dimensional array") type and a large set of fast, vectorized math functions that operate on whole arrays at once, instead of one value at a time. It's installed with pip install numpy and conventionally imported as import numpy as np.
The clearest way to see the difference is the same task, written both ways: computing the sum and average of a list of exam scores.
import numpy as np
scores = [88, 92, 79, 95, 84]
# The loop way (Chapter 9's accumulator pattern)
total = 0
for s in scores:
total += s
average = total / len(scores)
print("loop average:", average)
# The NumPy way
arr = np.array(scores)
print("arr.sum():", arr.sum(), "arr.mean():", arr.mean())
loop average: 87.6
arr.sum(): 438 arr.mean(): 87.6
Both approaches give the same answer here — the real payoff isn't this one line, it's what happens as the code grows:
- A loop-based version needs a new loop (or a new line inside the existing one) for every additional statistic — sum, then average, then standard deviation, then min and max each add more manual bookkeeping.
arr.sum(),arr.mean(),arr.std(),arr.min(), andarr.max()are each one call, already optimized, with no loop written by hand at all.- The same one-line pattern scales to a 2D grid of 40 students × 6 subjects without changing shape — Sub-topic 5 covers exactly this with the
axis=parameter.
arr.sum(), arr * 2) instead of writing an explicit loop that repeats the operation for every element. NumPy's speed advantage comes almost entirely from vectorization — the looping still happens, just inside fast, compiled C code instead of the slower Python interpreter.
Go Deeper: why is a Python loop actually slower here?
Every iteration of a plain Python for loop over a list
re-checks each element's type at runtime (since a list can mix
int, float, even str, in the
same list) and re-does Python's normal function-call overhead for
every +. A NumPy array locks in one fixed data type for
every element up front (see .dtype in Sub-topic 2), so
its vectorized operations skip that repeated type-checking entirely
and run as a tight, compiled loop instead — the core reason
for the large speed difference on anything beyond a handful of
values.
- NumPy provides the
ndarraytype: fixed-type, fixed-size arrays with fast, vectorized math built in. - A Python list is flexible but slow for numeric work; a NumPy array is faster because it skips per-element type-checking.
arr.sum()/arr.mean()replace a manual accumulator loop with one call each.
2. Creating arrays
np.array(a_list)builds an array from existing Python data;np.zeros(n)/np.ones(n)build arrays pre-filled with 0s or 1s.np.arange(start, stop, step)isrange()'s array equivalent;np.linspace(start, stop, count)generatescountevenly spaced values betweenstartandstop, inclusive.- Every array has a
.shape(dimensions), a.dtype(element type), and an.ndim(number of dimensions) — check these whenever an array isn't behaving as expected.
.shape/.dtype/.ndim early saves real debugging time later.
.shape, .dtype, and .ndim?
.shape is a tuple giving the size of each dimension (a flat list of 5 numbers has shape (5,); a 3-row, 2-column grid has shape (3, 2)). .dtype is the single data type every element shares (int64, float64, etc.). .ndim is how many dimensions the array has (1 for a flat list of numbers, 2 for a grid).
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print("np.array([1,2,3,4,5]) ->", a)
print("np.zeros(4) ->", np.zeros(4))
print("np.ones(3) ->", np.ones(3))
print("np.arange(0, 10, 2) ->", np.arange(0, 10, 2))
print("np.linspace(0, 1, 5) ->", np.linspace(0, 1, 5))
print("a.shape:", a.shape, "a.dtype:", a.dtype, "a.ndim:", a.ndim)
grid = np.array([[1, 2, 3], [4, 5, 6]])
print("grid.shape:", grid.shape, "grid.dtype:", grid.dtype, "grid.ndim:", grid.ndim)
np.array([1,2,3,4,5]) -> [1 2 3 4 5]
np.zeros(4) -> [0. 0. 0. 0.]
np.ones(3) -> [1. 1. 1.]
np.arange(0, 10, 2) -> [0 2 4 6 8]
np.linspace(0, 1, 5) -> [0. 0.25 0.5 0.75 1. ]
a.shape: (5,) a.dtype: int64 a.ndim: 1
grid.shape: (2, 3) grid.dtype: int64 grid.ndim: 2
Notice np.zeros()/np.ones() print with decimal
points (0., 1.) — they default to
float64, even though the values look whole. Passing a 2D
shape works exactly the same way, and this chapter's project builds a
2D grid the same way grid is built above — one row
per student, one column per subject.
Go Deeper: what's the difference between np.arange() and np.linspace()?
np.arange(start, stop, step) is defined by its
step size — you control the gap between values, and
the count of resulting values is whatever that produces.
np.linspace(start, stop, count) is defined by its
count — you control exactly how many evenly spaced
values you want (including both endpoints), and NumPy works out the
step size for you. Use arange() when you know the
step; use linspace() when you know how many points you
want.
np.array(),np.zeros(),np.ones(),np.arange(), andnp.linspace()are the core ways to build an array..shape/.dtype/.ndimdescribe an array's dimensions, element type, and number of dimensions.np.zeros()/np.ones()default tofloat64, even for whole-number values.
3. Indexing, slicing & boolean masking
- 1D indexing/slicing (
arr[1],arr[1:4]) works exactly like a Python list. - 2D indexing uses one comma-separated index,
grid[row, col], instead of Python's chainedgrid[row][col]. - Boolean masking —
arr[arr > 5]— is NumPy's single most important idiom: it filters an array using a condition, with no loop orifstatement written by hand.
1D indexing and slicing first, since they're already familiar from Chapter 7's lists:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print("arr[1]:", arr[1])
print("arr[1:4]:", arr[1:4])
print("arr[-1]:", arr[-1])
arr[1]: 20
arr[1:4]: [20 30 40]
arr[-1]: 50
2D indexing looks visually different, even though the idea is the same — "which row, which column":
grid2 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
grid2[1, 2] -- row 1, column 2 -> 6
grid2[0] -- entire row 0 -> [1 2 3]
grid2[:, 1] -- entire column 1 -> [2 5 8]
import numpy as np
grid2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print("grid2[1, 2]:", grid2[1, 2])
print("grid2[0]:", grid2[0])
print("grid2[:, 1]:", grid2[:, 1])
grid2[1, 2]: 6
grid2[0]: [1 2 3]
grid2[:, 1]: [2 5 8]
grid[:, 1]'s :?
A bare : in any position of a NumPy index means "every element along this dimension." grid[:, 1] reads as "every row, column 1" — the whole second column. grid[1, :] (or just grid[1]) reads as "row 1, every column" — the whole second row.
Now the most important idiom in this chapter: boolean
masking. Comparing an array to a value doesn't return one
True/False — it returns a whole new
array of True/False, one per element, called
a boolean mask. Using that mask as an index keeps
only the elements where it's True:
import numpy as np
arr = np.array([3, 8, 1, 9, 4, 7])
mask = arr > 5
print("mask:", mask)
print("arr[arr > 5]:", arr[arr > 5])
mask: [False True False True False True]
arr[arr > 5]: [8 9 7]
True/False values, the same shape as the array it was compared from, produced by a comparison like arr > 5. Using a boolean mask as an index — arr[mask], or directly arr[arr > 5] — returns only the elements where the mask is True, with zero explicit looping.
This one line, arr[arr > 5], replaces what would
otherwise be a full loop with an if check and a manually
built result list — and it reads directly as "give me the
elements greater than 5," which is exactly what it does.
- 1D indexing/slicing (
arr[i],arr[i:j]) works exactly like a Python list. - 2D indexing uses one comma,
grid[row, col], with:meaning "every element on this dimension." - A comparison like
arr > 5produces a boolean mask;arr[mask]filters using it, with no loop needed.
Go Deeper: can you combine multiple conditions in a mask?
Yes, using & (and) / | (or) instead of
Python's and/or keywords, with each
condition wrapped in parentheses:
arr[(arr > 5) & (arr < 9)] keeps only
elements greater than 5 AND less than 9. The parentheses are
required — without them, Python tries to evaluate
5 & arr first, which raises an error, since
& binds more tightly than the comparison operators
here.
- 1D indexing/slicing matches Python list syntax; 2D indexing uses one comma,
grid[row, col]. - A bare
:means "every element on this dimension." - Boolean masking (
arr[arr > 5]) filters an array by condition with no explicit loop — NumPy's single most-used idiom.
4. Vectorized math & broadcasting
- Arithmetic between an array and a single number (
arr + 5) applies to every element — no loop needed. - Arithmetic between two same-shaped arrays (
arr1 * arr2) operates element-by-element (position 0 with position 0, position 1 with position 1, and so on). - Broadcasting lets NumPy combine arrays of different but compatible shapes without you reshaping anything by hand — and raises a clear error when the shapes genuinely don't fit together.
import numpy as np
prices = np.array([10, 20, 30])
print("prices + 5:", prices + 5)
qty = np.array([2, 1, 3])
print("prices * qty:", prices * qty)
prices + 5: [15 25 35]
prices * qty: [20 20 90]
prices + 5 adds 5 to every element — the single
number 5 is "stretched" across the whole array. This
stretching is broadcasting, and it also works between
a 2D grid and a 1D array, as long as the 1D array's length matches the
grid's number of columns:
import numpy as np
grades = np.array([[70, 80], [90, 100]])
curve = np.array([5, 10])
print("grades + curve:", grades + curve)
grades + curve: [[ 75 90]
[ 95 110]]
Every row of grades got curve added to it:
curve[0] (5) added to each row's first column,
curve[1] (10) added to each row's second column. This only
works because curve's length (2) matches grades's
number of columns (2). When the shapes genuinely don't fit, NumPy
raises a clear error instead of guessing:
import numpy as np
try:
bad = np.array([1, 2, 3]) + np.array([1, 2])
except ValueError as e:
print("broadcast error:", e)
broadcast error: operands could not be broadcast together with shapes (3,) (2,)
A length-3 array and a length-2 array have no sensible way to line up
element-by-element, so NumPy raises a ValueError rather
than silently producing a wrong answer — the same
fail-loudly-not-silently instinct Chapter 12's exception handling
already taught.
- Array + number applies to every element; array + same-shaped array works element-by-element.
- Broadcasting stretches a smaller, compatible-shaped array across a larger one, with no manual copying.
- A genuine shape mismatch raises a
ValueErrornaming both shapes, rather than guessing at an answer.
Go Deeper: what's the general rule broadcasting follows?
NumPy compares two arrays' shapes from the rightmost
dimension inward. Two dimensions are compatible if they're equal, or
if one of them is 1 (a size-1 dimension gets stretched to match).
grades's shape is (2, 2) and
curve's shape is (2,) — NumPy treats
the missing leading dimension as size 1, so it compares
(2, 2) against (1, 2): the rightmost
dimensions match (2 and 2), and the size-1 dimension stretches to
cover both rows. This is the same rule behind every broadcasting
example in this chapter, just applied consistently.
- Array-and-number and same-shape array-and-array operations both apply element-by-element, with no loop written by hand.
- Broadcasting lets compatible different-shaped arrays combine, stretching the smaller one across the larger one.
- An incompatible shape mismatch raises a
ValueErrordescribing both shapes involved.
5. Aggregate functions & the axis= parameter
.sum(),.mean(),.min(),.max(), and.std()each collapse an array down to one summary number by default.- On a 2D grid,
axis=controls which dimension gets collapsed —axis=0collapses down the rows (one result per column);axis=1collapses across the columns (one result per row). - Getting
axis=0vs.axis=1backwards is the single most common NumPy mistake beginners make — the diagram below is worth studying before the explanation.
axis= lets one function call target either direction.
Before any explanation, here's the grid this section works with, and what each axis actually collapses:
col0 col1 col2
row0 90 85 92
row1 70 75 80
row2 88 91 95
axis=0 -- collapse DOWN the rows -- one result per COLUMN
axis=1 -- collapse ACROSS the columns -- one result per ROW
m.sum(axis=0) -> [248, 251, 267] (3 values: one per subject/column)
m.sum(axis=1) -> [267, 225, 274] (3 values: one per student/row)
With the picture in place, the rule in words: axis=0
walks down each column, adding up one value from every row — so
the result has one number per column (per subject, if columns are
subjects). axis=1 walks across each row, adding up one
value from every column — so the result has one number per row
(per student, if rows are students).
import numpy as np
m = np.array([[90, 85, 92], [70, 75, 80], [88, 91, 95]])
print("m.sum():", m.sum())
print("m.mean():", m.mean())
print("m.min():", m.min(), "m.max():", m.max())
print("m.std():", round(float(m.std()), 4))
print("m.sum(axis=0):", m.sum(axis=0))
print("m.sum(axis=1):", m.sum(axis=1))
print("m.mean(axis=0):", m.mean(axis=0))
print("m.mean(axis=1):", m.mean(axis=1))
m.sum(): 766
m.mean(): 85.11111111111111
m.min(): 70 m.max(): 95
m.std(): 7.9505
m.sum(axis=0): [248 251 267]
m.sum(axis=1): [267 225 274]
m.mean(axis=0): [82.66666667 83.66666667 89. ]
m.mean(axis=1): [89. 75. 91.33333333]
.std()?
Standard deviation (.std()) measures how spread out a set of values is around its mean — a small .std() means most values sit close to the average; a large one means they're spread widely. This chapter's project reports it alongside mean/min/max as a quick sense of how consistent a set of grades is, without needing to explain the underlying formula in depth.
Calling .sum()/.mean() with no
axis= at all collapses everything down to one
single number, across the whole grid — that's what m.sum()
and m.mean() did above, before axis= entered
the picture.
- No
axis=given: the aggregate collapses the entire array to one number. axis=0: collapses down the rows, one result per column.axis=1: collapses across the columns, one result per row.
Go Deeper: is there a memory trick for axis=0 vs. axis=1?
One that helps many people: axis=0 is the axis
named by the first number in .shape (the
row count) — and that's the dimension that disappears
from the result. A (3, 3) grid's axis=0
aggregate has shape (3,) (rows collapsed away, columns
remain); its axis=1 aggregate also has shape
(3,) here since the grid is square, but conceptually
it's "columns collapsed away, rows remain." The safest habit isn't
memorizing a trick at all, though — it's checking
result.shape after any axis= call the
first few times, until the pattern feels automatic.
.sum()/.mean()/.min()/.max()/.std()collapse an array to a single summary number by default.axis=0collapses down the rows (one result per column);axis=1collapses across the columns (one result per row).- Checking
result.shapeafter anaxis=call confirms which direction actually collapsed.
6. Reshaping & stacking arrays
.reshape(rows, cols)reinterprets the same data as a different shape, as long as the total element count matches..flatten()collapses any array back down to 1D.np.concatenate()joins arrays end-to-end;np.vstack()stacks arrays as new rows;np.hstack()stacks arrays as new columns (side by side).
.reshape()?
.reshape(rows, cols) returns the same underlying data, reinterpreted with a new shape — it doesn't reorder or recompute anything, it just changes how the same sequence of values is grouped into rows and columns. The total element count must stay the same: reshaping a 6-element array into (2, 3) works; reshaping it into (2, 4) raises an error, since 8 ≠ 6.
import numpy as np
flat = np.arange(6)
print("flat:", flat)
print("flat.reshape(2, 3):")
print(flat.reshape(2, 3))
print("flat.reshape(2,3).flatten():", flat.reshape(2, 3).flatten())
flat: [0 1 2 3 4 5]
flat.reshape(2, 3):
[[0 1 2]
[3 4 5]]
flat.reshape(2,3).flatten(): [0 1 2 3 4 5]
Stacking combines two or more separate arrays into one, and the three functions differ in exactly how they combine:
import numpy as np
a1 = np.array([1, 2])
a2 = np.array([3, 4])
print("np.concatenate([a1, a2]):", np.concatenate([a1, a2]))
print("np.vstack([a1, a2]):")
print(np.vstack([a1, a2]))
print("np.hstack([a1, a2]):", np.hstack([a1, a2]))
np.concatenate([a1, a2]): [1 2 3 4]
np.vstack([a1, a2]):
[[1 2]
[3 4]]
np.hstack([a1, a2]): [1 2 3 4]
np.concatenate([a1, a2])joins two 1D arrays end-to-end into one longer 1D array.np.vstack([a1, a2])stacks them as two separate rows of a new 2D grid.np.hstack([a1, a2])joins them side by side — for two 1D arrays, this looks identical toconcatenate, but the difference becomes visible once the inputs are already 2D.
Go Deeper: when would reshaping actually come up with real sensor data?
Imagine a sensor logging one temperature reading every hour, stored
as one flat array of 168 values (a full week, 24 × 7).
readings.reshape(7, 24) reinterprets that same flat
array as a grid — 7 rows (one per day), 24 columns (one per
hour) — with no data recomputed or moved, just regrouped. From
there, readings.reshape(7, 24).mean(axis=1) gives one
average temperature per day in a single line, using exactly the
axis= pattern from Sub-topic 5.
.reshape(rows, cols)reinterprets the same data with a new shape, as long as the element count matches;.flatten()collapses back to 1D.np.concatenate()joins end-to-end;np.vstack()stacks as new rows;np.hstack()joins side by side.- Reshaping is common when raw data arrives flat but needs to be grouped into a grid for per-group aggregate functions.
- Nearly every Python data-science and machine-learning library — pandas, scikit-learn, matplotlib, TensorFlow, PyTorch — either wraps NumPy arrays directly or uses the exact same array-shape and broadcasting conventions this chapter taught.
- Boolean masking is the everyday tool behind filtering real datasets: "every sensor reading above a safety threshold," "every transaction over $10,000," "every student who scored below passing" are all one-line
arr[condition]expressions. - The
axis=parameter is exactly how a real spreadsheet-style dataset (rows of records, columns of fields) gets summarized both "per record" and "per field" from the same underlying 2D array, without loading a separate library.
Points to Remember
- NumPy's
ndarraystores fixed-type data and runs vectorized operations in optimized C code, replacing manual Python loops for numeric work with single, fast calls likearr.sum()/arr.mean(). np.array(),np.zeros(),np.ones(),np.arange(), andnp.linspace()create arrays;.shape/.dtype/.ndimdescribe them.- 1D indexing/slicing matches list syntax; 2D indexing uses one comma (
grid[row, col]); boolean masking (arr[arr > 5]) filters by condition with no explicit loop — the single most important NumPy idiom. - Vectorized math applies element-by-element; broadcasting lets compatible different-shaped arrays combine automatically, and raises a clear
ValueErrorwhen shapes genuinely don't fit. .sum()/.mean()/.min()/.max()/.std()collapse an array to a summary number;axis=0collapses down the rows (one result per column),axis=1collapses across the columns (one result per row)..reshape()reinterprets the same data with a new shape;.flatten()collapses back to 1D;np.concatenate()/np.vstack()/np.hstack()combine separate arrays together.- NumPy underlies nearly every other Python data tool — the array-shape and broadcasting habits from this chapter carry forward directly into pandas (Chapter 24) and beyond.