🐍 Python for Everyone

← Back to all chapters

Chapter 23 of 28 Intermediate 75 min read

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

Picture Chapter 9's accumulator pattern: a 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.
Sub-topic 1 of 6

1. What NumPy is, and why it exists

At a glance
  • NumPy ("Numerical Python") provides the ndarray — a fixed-type, fixed-size array — plus fast, vectorized operations on it.
  • A Python list is 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.
Why this matters: nearly every other data tool in Python's ecosystem — pandas, scikit-learn, matplotlib, even parts of TensorFlow and PyTorch — is built directly on top of NumPy arrays. Understanding "why an array, not a list" here pays off in every chapter of data work that follows this one.
What is... NumPy? NumPy is a Python library providing the 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.

loop_vs_vectorized.py
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())
actual output of loop_vs_vectorized.py
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:

What is... vectorization? Vectorization is writing one operation that applies to an entire array at once (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.

Quick recap
  • NumPy provides the ndarray type: 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.
Sub-topic 2 of 6

2. Creating arrays

At a glance
  • 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) is range()'s array equivalent; np.linspace(start, stop, count) generates count evenly spaced values between start and stop, 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.
Why this matters: almost every NumPy bug traces back to an array having the wrong shape or dtype without you noticing — getting comfortable checking .shape/.dtype/.ndim early saves real debugging time later.
What is... .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).
creating_arrays.py
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)
actual output of creating_arrays.py
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.

try_it.py
Click "Run Code" — try building a 2D grid with np.array([[1,2],[3,4]]) and checking its .shape.
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.

Quick recap
  • np.array(), np.zeros(), np.ones(), np.arange(), and np.linspace() are the core ways to build an array.
  • .shape/.dtype/.ndim describe an array's dimensions, element type, and number of dimensions.
  • np.zeros()/np.ones() default to float64, even for whole-number values.
Sub-topic 3 of 6

3. Indexing, slicing & boolean masking

At a glance
  • 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 chained grid[row][col].
  • Boolean masking — arr[arr > 5] — is NumPy's single most important idiom: it filters an array using a condition, with no loop or if statement written by hand.
Why this matters: boolean masking is the idiom you'll reach for constantly in real data work — "give me every reading above a threshold," "give me every student who failed" — and it's the exact technique this chapter's project uses to separate above-average students from below-average ones.

1D indexing and slicing first, since they're already familiar from Chapter 7's lists:

indexing_1d.py
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])
actual output of indexing_1d.py
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":

a 2D grid, by position
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]
indexing_2d.py
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])
actual output of indexing_2d.py
grid2[1, 2]: 6
grid2[0]: [1 2 3]
grid2[:, 1]: [2 5 8]
What is... 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:

boolean_masking.py
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])
actual output of boolean_masking.py
mask: [False  True False  True False  True]
arr[arr > 5]: [8 9 7]
What is... a boolean mask? A boolean mask is an array of 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.

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.

Quick recap
  • 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.
Sub-topic 4 of 6

4. Vectorized math & broadcasting

At a glance
  • 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.
Why this matters: vectorized math is where NumPy's speed and readability advantage becomes obvious in everyday code — a whole grid of measurements adjusted, scaled, or combined in a single line, instead of a nested loop over rows and columns.
vectorized_math.py
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)
actual output of vectorized_math.py
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:

What is... broadcasting? Broadcasting is NumPy's rule for combining arrays of different shapes in an arithmetic operation, by conceptually "stretching" the smaller array across the larger one's shape, without actually copying any data. A single number broadcasts across an entire array; a 1D array broadcasts across each row of a 2D grid, as long as its length matches the grid's row length (number of columns).
broadcasting.py
import numpy as np

grades = np.array([[70, 80], [90, 100]])
curve = np.array([5, 10])
print("grades + curve:", grades + curve)
actual output of broadcasting.py -- curve stretched across every row
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:

broadcasting_error.py
import numpy as np

try:
    bad = np.array([1, 2, 3]) + np.array([1, 2])
except ValueError as e:
    print("broadcast error:", e)
actual output of broadcasting_error.py
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.

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.

Quick recap
  • 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 ValueError describing both shapes involved.
Sub-topic 5 of 6

5. Aggregate functions & the axis= parameter

At a glance
  • .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=0 collapses down the rows (one result per column); axis=1 collapses across the columns (one result per row).
  • Getting axis=0 vs. axis=1 backwards is the single most common NumPy mistake beginners make — the diagram below is worth studying before the explanation.
Why this matters: this chapter's project reports per-subject AND per-student statistics from the same 2D grid of grades — that's only possible because 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:

axis=0 vs. axis=1, on a 3-student x 3-subject grid
           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).

aggregates_and_axis.py
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))
actual output of aggregates_and_axis.py
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]
What is... .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.

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.

Quick recap
  • .sum()/.mean()/.min()/.max()/.std() collapse an array to a single summary number by default.
  • axis=0 collapses down the rows (one result per column); axis=1 collapses across the columns (one result per row).
  • Checking result.shape after an axis= call confirms which direction actually collapsed.
Sub-topic 6 of 6

6. Reshaping & stacking arrays

At a glance
  • .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).
Why this matters: real data rarely arrives already shaped the way you need it — a flat list of sensor readings might need reshaping into a grid of one row per day, or several separate readings might need combining into one array before running aggregate functions on the whole set.
What is... .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.
reshape_flatten.py
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())
actual output of reshape_flatten.py
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:

stacking.py
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]))
actual output of stacking.py
np.concatenate([a1, a2]): [1 2 3 4]
np.vstack([a1, a2]):
[[1 2]
 [3 4]]
np.hstack([a1, a2]): [1 2 3 4]
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.

Quick recap
  • .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.
In the Real World

Points to Remember

← All Chapters Take the Quiz →