Skip to content

23. NumPy

This module starts Part 4. Until now you stored data in lists and dicts and processed it with loops. NumPy stores numbers in compact arrays and processes a whole array with one operation. pandas, scikit-learn, SciPy, Matplotlib and PyTorch are all built on this idea, so everything in Parts 4 and 5 rests on this module. The examples use the course datasets: sensor readings, a stores × months sales matrix and house prices.

  • Create NumPy arrays from lists and files, read their shape and dtype, and predict their memory use.
  • Select data with indexing, slicing, boolean masks and fancy indexing, and know when you get a view and when you get a copy.
  • Replace Python loops with vectorized operations and broadcasting, and measure the speed-up.
  • Aggregate along an axis, handle missing values with nan functions, and reshape, stack and split arrays.
  • Use @, solve, lstsq, eigh and svd to fit a least-squares line and to find the main pattern in a matrix.
  • Generate reproducible random numbers with np.random.default_rng(42).

A Python list can hold anything: numbers, strings, other lists. Each item is a separate Python object somewhere in memory, and the list stores a pointer to each one. A loop over a list must look at every object, check its type and call the right + or *. For a few values this does not matter. For a million sensor readings it is slow.

NumPy (Numerical Python) is a library for numeric data. Its core type is the ndarray (n-dimensional array), usually just called an array. An array differs from a list in three ways:

  • It is homogeneous: every element (one value in the array) has the same type, for example 64-bit floats.
  • It stores the raw numbers in one contiguous block of memory: one number after the other, with no pointers and no per-value objects.
  • Its operations run as loops in compiled C code over that block. You write one expression, such as temps * 2, and NumPy applies it to every element.

The convention is to import NumPy as np. The first block also sets print options: precision=3 shows at most 3 decimals and suppress=True avoids scientific notation such as 2.5e+01. These options change only how arrays print, never the stored values.

import numpy as np
np.set_printoptions(precision=3, suppress=True)
readings = [20.21, 20.22, 20.16, 19.93, 19.90, 20.12] # S1, 00:00 to 00:50
print(readings * 2)
temps = np.array(readings)
print(temps * 2)
print(temps * 9 / 5 + 32)
print(type(temps))
Output
[20.21, 20.22, 20.16, 19.93, 19.9, 20.12, 20.21, 20.22, 20.16, 19.93, 19.9, 20.12]
[40.42 40.44 40.32 39.86 39.8 40.24]
[68.378 68.396 68.288 67.874 67.82 68.216]
<class 'numpy.ndarray'>

The six values are the first hour of sensor S1 in data/sensors.csv. For a list, * 2 repeats the list. For an array, * 2 doubles every element. The Fahrenheit conversion works on all six values with no loop. An operation that works on each element separately, like this one, is element-wise.

Python list NumPy array
Items any objects, mixed types one dtype for all elements
Memory pointers to separate objects one contiguous block of raw numbers
x * 2 repeats the list doubles every element
x + y joins the lists adds element by element (same shape)
Speed of math on 1 million values slow: one Python step per value fast: one C loop
Size grows with append fixed; “adding” builds a new array

An array can have any number of dimensions. A list of readings is 1-dimensional. A table is 2-dimensional: rows and columns. NumPy calls each dimension an axis. Axis 0 runs down the rows and axis 1 runs across the columns. The shape is a tuple with the length of each axis.

The next array is a small sales matrix: the real 2024 revenue (USD, rounded) of the three North stores, by quarter. Each row is a store (S01 Chicago, S02 Minneapolis, S03 Detroit). Each column is a quarter (Q1 to Q4). A matrix is a 2-dimensional array of numbers.

sales_q = np.array([
[40722, 45357, 52453, 82368], # S01
[21926, 27811, 33103, 58803], # S02
[16664, 34934, 24725, 38865], # S03
])
print(sales_q)
print("shape:", sales_q.shape, "ndim:", sales_q.ndim, "size:", sales_q.size)
print("len:", len(sales_q), "temps shape:", temps.shape)
Output
[[40722 45357 52453 82368]
[21926 27811 33103 58803]
[16664 34934 24725 38865]]
shape: (3, 4) ndim: 2 size: 12
len: 3 temps shape: (6,)

shape is (3, 4): 3 rows and 4 columns. ndim is the number of axes and size the number of elements. len() gives the length of axis 0 only. A 1-dimensional shape is written (6,): a tuple with one item, so the comma is needed.

You often start from a pattern instead of typed values:

print(np.zeros(4)) # 4 zeros, float64
print(np.ones((2, 3), dtype=np.int64)) # shape (2, 3), integers
print(np.full(3, np.nan)) # a placeholder for missing values
print(np.arange(0, 60, 10)) # like range(): minutes of the first hour
print(np.linspace(19.0, 23.0, 5)) # 5 evenly spaced values, both ends included
print(np.eye(3)) # the 3 x 3 identity matrix
Output
[0. 0. 0. 0.]
[[1 1 1]
[1 1 1]]
[nan nan nan]
[ 0 10 20 30 40 50]
[19. 20. 21. 22. 23.]
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]

np.arange(start, stop, step) works like range(): the stop value is not included. np.linspace(start, stop, num) includes both ends and is better for floats, because a float step can add rounding errors. np.eye(3) is the identity matrix: 1 on the diagonal, 0 elsewhere. It plays the role of the number 1 in matrix multiplication.

Every array has a dtype (data type): the type of all its elements. NumPy picks one from the data. You can also choose one with dtype= or convert with .astype().

print(temps.dtype, sales_q.dtype)
print(np.array([1, 2.5]).dtype) # an int and a float give float64
print(np.array(["S1", "S2"]).dtype) # text: Unicode, at most 2 characters
print(np.array([True, False]).dtype)
print(sales_q.itemsize, sales_q.nbytes) # bytes per element, bytes in total
Output
float64 int64
float64
<U2
bool
8 96

float64 is a 64-bit float, the same as a Python float. int64 is a 64-bit integer. In <U2, U means Unicode text and 2 is the maximum number of characters. Each element of sales_q takes 8 bytes (itemsize), so 12 elements take 96 bytes (nbytes).

dtype Bytes Range or precision Typical data
bool 1 True/False flags, masks
int8 1 −128 to 127 small codes, ratings 1–5
int32 4 about ±2.1 billion counts, ids
int64 8 about ±9.2 × 10¹⁸ the default integer
float32 4 about 7 significant digits images, neural networks
float64 8 about 15–17 significant digits the default float; measurements, prices in analysis (integer cents or Decimal for accounting)
<U10 40 up to 10 characters labels (pandas and Polars handle text better)

Memory is where arrays shine. One column of data/sensors.csv has 8,064 values. Compare the array with a list of the same values:

import sys
column = np.zeros(8064) # one float per row of data/sensors.csv
as_list = column.tolist()
list_bytes = sys.getsizeof(as_list) + sum(sys.getsizeof(x) for x in as_list)
print("array:", column.nbytes, "bytes")
print("list: ", list_bytes, "bytes")
print("float32 array:", column.astype(np.float32).nbytes, "bytes")
Output
array: 64512 bytes
list: 258104 bytes
float32 array: 32256 bytes

The array stores 8 bytes per value. The list stores an 8-byte pointer per value plus a 24-byte float object for each one, so it needs about 4 times more memory. astype(np.float32) halves the array again, at the cost of precision. astype() always returns a new array; the original keeps its dtype.

Small integer types save memory, but they overflow: a result that does not fit wraps around to the other end of the range, with no error and no warning.

units = np.array([100, 120, 90], dtype=np.int8)
print(units.nbytes, np.iinfo(np.int8).max)
print(units + units) # 200 does not fit in int8
print(units.astype(np.int64) + units) # upcast first
print(units.sum(), units.sum().dtype) # sum() uses a wider integer
Output
3 127
[-56 -16 -76]
[200 240 180]
310 int64

np.iinfo() shows the limits of an integer dtype. 100 + 100 gives -56 because 200 wraps around past 127. This is integer overflow. It is a silent bug: the code runs and the numbers are wrong. Convert to a wider dtype before the arithmetic. sum() is safe here because it accumulates small integers in int64.

NumPy 2 refuses a Python integer that cannot fit at all:

print(units + 300)
Output
OverflowError: Python integer 300 out of bounds for int8

When an operation mixes two dtypes, NumPy picks the result dtype. This is type promotion. NumPy 2 follows two rules (written down in the proposal NEP 50):

  • Two arrays (or NumPy scalars such as np.float64(1)): the result is the smallest dtype that can hold both. int8 with int16 gives int16, int8 with float32 gives float32, and int64 with float32 gives float64.
  • An array and a plain Python int or float: when the kinds match (int with int, float with float), the Python number takes the array’s dtype. That is why units + 300 fails instead of promoting, and why a float32 array times 2.0 stays float32. A Python float with an integer array gives float64.
f32 = np.ones(3, dtype=np.float32)
print((units + 5).dtype, (units + 1.5).dtype) # Python int, Python float
print((f32 * 2.0).dtype, (units + f32).dtype) # float kind kept; int8 + float32
print((units + np.int16(1)).dtype, (np.ones(3, dtype=np.int64) + f32).dtype)
Output
int8 float64
float32 float32
int16 float64

astype() from float to int truncates (drops the decimals toward zero). Round first if you want the nearest integer:

prices = np.array([79.99, 249.0, 12.5])
print(prices.astype(np.int64))
print(np.round(prices).astype(np.int64))
Output
[ 79 249 12]
[ 80 249 12]

np.round() rounds halves to the even number, like Python’s round(): 12.5 becomes 12.

total = sales_q.sum()
print(total)
print(repr(total), repr(temps[0]))
print([temps[0], float(temps[0])])
print(f"Total: {total:,} USD")
Output
477731
np.int64(477731) np.float64(20.21)
[np.float64(20.21), 20.21]
Total: 477,731 USD

Real arrays come from files. data/sensors.csv has 6 columns: timestamp, sensor_id, temperature_c, humidity_pct, vibration_mm_s and status. An array has one dtype, so you load the numeric columns into one float array and each text column into its own array.

np.genfromtxt() reads a text file into an array. delimiter="," splits the columns, skip_header=1 skips the header row and usecols picks columns by position (0-based).

data = np.genfromtxt(
"data/sensors.csv", delimiter=",", skip_header=1, usecols=(2, 3, 4)
)
print(data.shape, data.dtype)
print(data[:3])
Output
(8064, 3) float64
[[20.21 57.1 2.5 ]
[22.3 58.4 3.39]
[19.4 56.9 1.65]]

The result has one row per reading and one column per measurement: temperature, humidity and vibration. genfromtxt turns a blank cell into nan (see the next section). np.loadtxt() is the faster, stricter reader. It stops at the first blank cell:

strict = np.loadtxt(
"data/sensors.csv", delimiter=",", skiprows=1, usecols=(2, 3, 4)
)
Output
ValueError: could not convert string '' to float64 at row 101, column 3.

Text columns load with dtype=str. They have no blanks, so loadtxt works:

timestamps = np.loadtxt(
"data/sensors.csv", delimiter=",", skiprows=1, usecols=0, dtype=str
)
sensor_ids = np.loadtxt(
"data/sensors.csv", delimiter=",", skiprows=1, usecols=1, dtype=str
)
status = np.loadtxt(
"data/sensors.csv", delimiter=",", skiprows=1, usecols=5, dtype=str
)
print(timestamps[:2], sensor_ids[:6], status[:3])
print(sensor_ids.dtype, len(timestamps))
Output
['2024-05-01T00:00:00' '2024-05-01T00:00:00'] ['S1' 'S2' 'S3' 'S4' 'S1' 'S2'] ['ok' 'ok' 'ok']
<U2 8064
Reader Blank cells Speed Use it for
np.loadtxt error fast clean numeric files, text columns with no blanks
np.genfromtxt nan (or a value you choose with filling_values) slower numeric columns with gaps
csv module, then np.array(...) you decide in Python slowest mixed rows, conversions per field
pd.read_csv (module 24) NaN fast real tables with mixed types: the usual choice

NumPy is not a table library. For mixed columns, module 24 uses pandas, which stores each column as an array with its own dtype.

A float array marks a missing value with NaN (Not a Number), written np.nan. Module 09 met it as float("nan"). Any arithmetic with NaN gives NaN, so one gap spoils a whole sum or mean. NumPy has a nan function for each common aggregation: it skips NaN values.

temperature = data[:, 0]
humidity = data[:, 1]
vibration = data[:, 2]
print("missing per column:", np.isnan(data).sum(axis=0))
print("mean:", temperature.mean())
print(f"nanmean: {np.nanmean(temperature):.2f}")
print(f"nanmax: {np.nanmax(temperature)}, nanmin: {np.nanmin(temperature)}")
print(np.nan == np.nan, np.isnan(np.nan))
Output
missing per column: [22 29 30]
mean: nan
nanmean: 24.06
nanmax: 44.89, nanmin: 18.56
False True

data[:, 0] takes column 0 of every row (see Indexing and slicing). np.isnan() gives True where a value is missing. sum(axis=0) counts the True values per column (Aggregations explains axis): 22, 29 and 30 blanks, as the data dictionary says. The plain mean() is nan. nanmean() gives 24.06 °C. NaN is not equal to itself, so x == np.nan never finds a gap. Always use np.isnan(x).

Plain NaN-aware Plain NaN-aware
np.sum np.nansum np.min, np.max np.nanmin, np.nanmax
np.mean np.nanmean np.argmin, np.argmax np.nanargmin, np.nanargmax
np.median np.nanmedian np.percentile np.nanpercentile
np.std, np.var np.nanstd, np.nanvar np.cumsum np.nancumsum

Integer and boolean arrays cannot hold NaN. That is why genfromtxt returns floats, and why pandas turns an integer column with blanks into float64.

Indexing picks one element; slicing picks a range. On one axis, the rules are those of lists: positions start at 0, negative positions count from the end and start:stop:step excludes stop. A 2-dimensional array takes one index or slice per axis, separated by a comma: [rows, columns].

print(temps[0], temps[-1])
print(temps[1:4])
print(temps[::2])
print(sales_q[0, 3]) # row 0 (S01), column 3 (Q4)
print(sales_q[1]) # row 1: S02, all quarters
print(sales_q[:, 3]) # column 3: Q4, all stores
print(sales_q[:2, 2:]) # S01-S02, Q3-Q4
Output
20.21 20.12
[20.22 20.16 19.93]
[20.21 20.16 19.9 ]
82368
[21926 27811 33103 58803]
[82368 58803 38865]
[[52453 82368]
[33103 58803]]

sales_q[:, 3] reads “all rows, column 3”. The result is 1-dimensional: one value per store. sales_q[0, 3] is the fast form of sales_q[0][3]. The second form first builds row 0 and then indexes it.

For lists, a slice is a new list. For arrays, a basic slice is a view: a new array object that shares the memory of the original array. A view costs almost nothing, even for a slice of a billion values. But a change through the view changes the original too. A copy has its own memory.

q4 = sales_q[:, 3]
q4[0] = 0
print(sales_q[0])
print(np.shares_memory(q4, sales_q), q4.base is sales_q)
sales_q[0, 3] = 82368 # restore the real value
q4_copy = sales_q[:, 3].copy()
q4_copy[0] = 0
print(sales_q[0, 3], np.shares_memory(q4_copy, sales_q))
Output
[40722 45357 52453 0]
True True
82368 False

np.shares_memory(a, b) tells you whether two arrays use the same memory. The attribute .base of a view is the array that owns the memory. .copy() makes an independent array.

You get a view You get a copy
basic slicing: a[2:5], a[:, 0], a[::2] boolean masks: a[a > 0]
a.reshape(...) when the memory layout allows it fancy indexing: a[[0, 2]]
a.T, a.ravel() on a contiguous array a.copy(), a.flatten(), a.astype(...)
arithmetic results: a * 2

A comparison between an array and a value is element-wise. It returns a boolean array of the same shape. Used as an index, a boolean array is a boolean mask: it keeps the elements where the mask is True. Masks replace the if inside a loop.

hot = temperature >= 33
print(hot[:6], hot.dtype)
print("hot readings:", hot.sum(), f"share: {hot.mean():.4f}")
print(temperature[hot][:5])
Output
[False False False False False False] bool
hot readings: 36 share: 0.0045
[38.03 33.51 36.03 44.89 36.82]

True counts as 1 and False as 0. So mask.sum() counts the matches and mask.mean() gives their share. temperature[hot] keeps only the 36 hot readings, in their original order. A comparison with NaN is False, so missing readings never pass a filter.

Combine masks with & (and), | (or) and ~ (not). Put every comparison in parentheses:

is_s4 = sensor_ids == "S4"
print("S4 and hot:", (is_s4 & hot).sum())
print("S4 or hot:", (is_s4 | hot).sum())
print("not S4:", (~is_s4).sum())
print("missing temperature:", np.isnan(temperature).sum())
Output
S4 and hot: 8
S4 or hot: 2044
not S4: 6048
missing temperature: 22

The words and, or and not do not work on arrays. They ask for one True or False for the whole array, and NumPy refuses to guess:

print(is_s4 and hot)
Output
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The parentheses matter because & binds more tightly than >=. temperature >= 33 & is_s4 means temperature >= (33 & is_s4), which compares each temperature with 0 or 1. It runs with no error and gives 8,042 “matches”. Write (temperature >= 33) & is_s4.

np.any() and np.all() reduce a mask to one bool. A mask can also be on the left of =, to change only the selected elements:

clean = temperature.copy()
clean[clean > 40] = np.nan # treat impossible values as missing
print(np.any(temperature > 40), np.all(np.isnan(clean[temperature > 40])))
print(f"{np.isnan(clean).sum()} missing after cleaning")
Output
True True
28 missing after cleaning

Vectorization means writing an operation on whole arrays instead of a loop over elements. The loop still happens, but in C, inside NumPy. A universal function (ufunc) is a NumPy function that works element-wise on arrays of any shape: np.sqrt, np.log, np.exp, np.abs, np.round, np.maximum and the operators +, -, *, /, **, >, ==.

print(temperature[:4] * 9 / 5 + 32)
print(np.sqrt(vibration[:4]))
print(np.log(vibration[:4]))
print(np.maximum(temperature[:4], 22.0)) # element-wise max of two arrays
Output
[68.378 72.14 66.92 76.136]
[1.581 1.841 1.285 1.473]
[0.916 1.221 0.501 0.775]
[22. 22.3 22. 24.52]

np.maximum(a, b) compares two arrays element by element. Do not confuse it with np.max(a), which reduces one array to its largest value.

How much faster is it? Time a Python list comprehension and the NumPy expression on the 8,042 valid temperatures. The timeit module from module 15 runs each one 50 times:

import timeit
valid = temperature[~np.isnan(temperature)]
valid_list = valid.tolist()
def loop_fahrenheit(values: list[float]) -> list[float]:
return [v * 9 / 5 + 32 for v in values]
t_loop = timeit.timeit(lambda: loop_fahrenheit(valid_list), number=50) / 50
t_numpy = timeit.timeit(lambda: valid * 9 / 5 + 32, number=50) / 50
print(f"Python loop: {t_loop * 1000:.3f} ms per run")
print(f"NumPy: {t_numpy * 1000:.3f} ms per run")
print("NumPy is faster:", t_numpy < t_loop)
print("Same values:", np.allclose(loop_fahrenheit(valid_list), valid * 9 / 5 + 32))
Output
Python loop: 0.316 ms per run
NumPy: 0.006 ms per run
NumPy is faster: True
Same values: True

The exact times depend on your machine. In the run that produced this page it was about 60 times faster; your machine will give other numbers, and the gap grows with the data. np.allclose(a, b) checks that two arrays are equal within a small float tolerance, like math.isclose() for arrays.

An aggregation (or reduction) turns many values into one: a sum, a mean, a maximum. With no axis, it reduces the whole array. With axis=0, it collapses the rows and gives one result per column. With axis=1, it collapses the columns and gives one result per row.

flowchart LR
    A["sales_q<br/>shape (3, 4)<br/>3 stores x 4 quarters"] -->|"sum(axis=0)<br/>collapse rows"| B["shape (4,)<br/>one total per quarter"]
    A -->|"sum(axis=1)<br/>collapse columns"| C["shape (3,)<br/>one total per store"]
    A -->|"sum()<br/>no axis"| D["one number<br/>grand total"]

A memory aid: the axis you name is the axis that disappears.

print(sales_q.sum())
print(sales_q.sum(axis=0)) # per quarter: down the rows
print(sales_q.sum(axis=1)) # per store: across the columns
print(sales_q.mean(axis=1))
print(sales_q.argmax(axis=1)) # position of the best quarter per store
print(sales_q.cumsum(axis=1)) # year-to-date revenue per store
Output
477731
[ 79312 108102 110281 180036]
[220900 141643 115188]
[55225. 35410.75 28797. ]
[3 3 3]
[[ 40722 86079 138532 220900]
[ 21926 49737 82840 141643]
[ 16664 51598 76323 115188]]

argmax returns a position, not a value. All three stores had their best quarter in position 3 (Q4). cumsum keeps the shape: each column holds the running total up to that quarter.

Method Gives Method Gives
sum, prod total, product argmin, argmax position of the smallest, largest
mean, median (function only: np.median) center cumsum, cumprod running total, product (same shape)
min, max, ptp (function only: np.ptp) extremes, range np.percentile(a, q) value below which q% of the data lies
std, var spread (ddof=0 by default) any, all reduce a mask to bool
s01 = sales_q[0]
print(f"ddof=0: {s01.std():.1f} ddof=1: {s01.std(ddof=1):.1f}")
totals = sales_q.sum(axis=1, keepdims=True)
print(totals.shape)
print(totals)
Output
ddof=0: 16218.4 ddof=1: 18727.3
(3, 1)
[[220900]
[141643]
[115188]]

keepdims=True keeps the reduced axis with length 1. The totals stay a column of shape (3, 1) instead of a flat (3,). The next sections show why that shape is useful.

Fancy indexing selects elements with an array (or list) of integer positions. The positions can come in any order and can repeat. It is how you reorder rows, pick the top items or look values up in a table. Fancy indexing always returns a copy.

stores = np.array(["S01", "S02", "S03"])
year_total = sales_q.sum(axis=1)
order = np.argsort(year_total)[::-1] # positions from largest to smallest
print(order)
print(stores[order], year_total[order])
print(sales_q[[2, 0]]) # rows S03 and S01, in that order
print(sales_q[:, [3, 0]]) # columns Q4 and Q1
print(sales_q[[0, 1], [3, 0]]) # pairs: (S01, Q4) and (S02, Q1)
Output
[0 1 2]
['S01' 'S02' 'S03'] [220900 141643 115188]
[[16664 34934 24725 38865]
[40722 45357 52453 82368]]
[[82368 40722]
[58803 21926]
[38865 16664]]
[82368 21926]

np.argsort() returns the positions that would sort the array, smallest first; [::-1] reverses them. Indexing two arrays with the same order keeps the labels and the values aligned. The last line surprises many people: two index lists pick pairs of positions, not a 2 × 2 block. To get a block, select in two steps (sales_q[[0, 1]][:, [3, 0]]) or use np.ix_([0, 1], [3, 0]).

A lookup table is an array that you index with codes. Fancy indexing turns codes into values for millions of rows in one step:

unit_price = np.array([79.99, 249.00, 1299.00]) # P001, P002, P003
product_code = np.array([0, 2, 0, 1, 0]) # five order lines
print(unit_price[product_code])
Output
[ 79.99 1299. 79.99 249. 79.99]

So far, array arithmetic used two arrays of the same shape, or an array and one number. Broadcasting is the set of rules that lets NumPy combine arrays of different shapes. NumPy stretches the smaller array along the missing or length-1 axes, without copying data.

The rule compares the shapes from the right, axis by axis. Two axes are compatible when they are equal or when one of them is 1. A missing axis on the left counts as 1.

flowchart TD
    A["Align the shapes on the right<br/>(3, 4) and (4,) become (3, 4) and (1, 4)"] --> B{"For each axis:<br/>equal, or one of them is 1?"}
    B -->|yes, every axis| C["Stretch the length-1 axes<br/>result shape: the max of each axis"]
    B -->|no, for any axis| D["ValueError: operands could<br/>not be broadcast together"]
Shape A Shape B Result Meaning
(3, 4) () (a number) (3, 4) the number applies to every element
(3, 4) (4,) (3, 4) the row repeats for every row: one value per column
(3, 4) (3, 1) (3, 4) the column repeats for every column: one value per row
(3, 1) (4,) (3, 4) an outer table: every row value with every column value
(3, 4) (3,) error the right-most axes are 4 and 3

Three common uses on the sales matrix:

print(sales_q / 1000) # (3, 4) with a number
quarter_mean = sales_q.mean(axis=0) # shape (4,)
print(sales_q - quarter_mean) # each store against the quarter mean
share = sales_q / sales_q.sum(axis=1, keepdims=True) # (3, 4) / (3, 1)
print(share)
print(share.sum(axis=1))
Output
[[40.722 45.357 52.453 82.368]
[21.926 27.811 33.103 58.803]
[16.664 34.934 24.725 38.865]]
[[ 14284.667 9323. 15692.667 22356. ]
[ -4511.333 -8223. -3657.333 -1209. ]
[ -9773.333 -1100. -12035.333 -21147. ]]
[[0.184 0.205 0.237 0.373]
[0.155 0.196 0.234 0.415]
[0.145 0.303 0.215 0.337]]
[1. 1. 1.]

The (4,) array of quarter means is subtracted from every row. The (3, 1) column of store totals divides every column of its row. Each store’s shares add up to 1. Without keepdims, the totals have shape (3,), and NumPy aligns them with the 4 columns:

print(sales_q / sales_q.sum(axis=1))
Output
ValueError: operands could not be broadcast together with shapes (3,4) (3,)

The fix is keepdims=True, or totals[:, np.newaxis] to add an axis of length 1. np.newaxis is an alias for None in an index.

An outer table shows every combination of two lists. Here: the price of 3 products at the 4 discount levels of data/sales.csv.

price = np.array([79.99, 249.00, 1299.00])
discount = np.array([0.0, 0.05, 0.1, 0.2])
print(price[:, np.newaxis] * (1 - discount)) # (3, 1) * (4,) -> (3, 4)
Output
[[ 79.99 75.99 71.991 63.992]
[ 249. 236.55 224.1 199.2 ]
[1299. 1234.05 1169.1 1039.2 ]]

The most common use in machine learning is standardization, which module 18 computed one value at a time: give every column (feature) mean 0 and standard deviation 1, so that features with big units do not dominate. Each value becomes a z-score, the number of standard deviations from its column mean:

zij=xij−μjσjz_{ij} = \frac{x_{ij} - \mu_j}{\sigma_j}

Here xijx_{ij} is row ii of column jj, and μj\mu_j and σj\sigma_j are the mean and standard deviation of column jj. In NumPy, the (3,) row of means and the (3,) row of deviations broadcast over all 8,064 rows:

mu = np.nanmean(data, axis=0) # shape (3,): one mean per column
sigma = np.nanstd(data, axis=0) # shape (3,)
z = (data - mu) / sigma # (8064, 3) with (3,)
print(mu, sigma)
print(z[:3])
print(np.nanmean(z, axis=0).round(6), np.nanstd(z, axis=0))
Output
[24.055 54.14 2.724] [2.578 3.714 1.399]
[[-1.492 0.797 -0.16 ]
[-0.681 1.147 0.476]
[-1.806 0.743 -0.768]]
[-0. -0. 0.] [1. 1. 1.]

After the transformation, every column has mean 0 and standard deviation 1. A reading with z=2z = 2 is two standard deviations above its column mean, whatever the unit. NaN stays NaN. scikit-learn’s StandardScaler (module 34) computes exactly this.

reshape() gives the same elements a new shape. The number of elements must stay the same. One axis can be -1: NumPy computes it. data/sensors.csv is sorted by timestamp and then by sensor, so the temperature column repeats the pattern S1, S2, S3, S4. A reshape turns it into a timestamp × sensor matrix:

by_sensor = temperature.reshape(-1, 4) # rows: timestamps, columns: S1..S4
print(by_sensor.shape)
print(by_sensor[:2])
by_day = by_sensor.reshape(14, 144, 4) # 14 days x 144 ten-minute slots x 4 sensors
print(by_day.shape)
print(np.shares_memory(by_day, temperature))
print(by_sensor.ravel().shape, sales_q.T.shape)
Output
(2016, 4)
[[20.21 22.3 19.4 24.52]
[20.22 22.44 19.46 24.63]]
(14, 144, 4)
True
(8064,) (4, 3)

Reshape reads and writes the elements in row order (the last axis changes fastest). That order matches the file, so each row of by_sensor holds one timestamp. A day has 144 ten-minute slots, so (14, 144, 4) is a 3-dimensional array: day, slot, sensor. The reshape is a view, so it costs nothing. ravel() flattens back to 1 dimension. .T is the transpose: rows become columns.

Joining and splitting:

h1 = sales_q[:, :2] # Q1-Q2
h2 = sales_q[:, 2:] # Q3-Q4
print(np.concatenate([h1, h2], axis=1).shape) # join along an existing axis
print(np.concatenate([h1, h2], axis=0).shape)
halves = np.stack([h1.sum(axis=1), h2.sum(axis=1)], axis=1) # a new axis
print(halves)
first, second = np.split(sales_q, 2, axis=1) # equal parts
print(first.shape, np.array_equal(first, h1))
print([len(part) for part in np.array_split(np.arange(10), 3)])
Output
(3, 4)
(6, 2)
[[ 86079 134821]
[ 49737 91906]
[ 51598 63590]]
(3, 2) True
[4, 3, 3]
Function Does Shapes
np.concatenate([a, b], axis=k) joins along an existing axis (3, 2) + (3, 2) on axis 1 → (3, 4)
np.stack([a, b], axis=k) adds a new axis two (3,) on axis 1 → (3, 2)
np.vstack, np.hstack stack rows, stack columns shortcuts for common cases
np.column_stack([x, y]) 1-D arrays as columns two (n,) → (n, 2)
np.split(a, n, axis=k) n equal parts fails if the length is not divisible
np.array_split(a, n) n nearly equal parts 10 into 3 → 4, 3, 3

np.array_equal(a, b) is True when two arrays have the same shape and the same elements.

np.where(condition, a, b) is a vectorized if/else: it takes a where the condition is True and b elsewhere. With one argument, np.where(condition) returns the positions where the condition holds.

label = np.where(temperature >= 33, "hot", "normal")
print(label[:3], (label == "hot").sum())
filled = np.where(np.isnan(temperature), np.nanmedian(temperature), temperature)
print(np.isnan(filled).sum())
print(np.where(temperature >= 42)[0]) # row positions of the hottest readings
Output
['normal' 'normal' 'normal'] 36
0
[ 897 1539]

np.select(conditions, choices, default=...) is the vectorized if/elif/else. It checks the conditions in order and takes the choice of the first one that is True. The data dictionary gives the rule behind the status column of data/sensors.csv. Rebuild it:

rule = np.select(
[
(vibration >= 11.2) | (temperature >= 42),
(vibration >= 4.5) | (temperature >= 33),
],
["fail", "warn"],
default="ok",
)
print(np.unique(rule, return_counts=True))
print("matches the file:", (rule == status).sum(), "of", len(status))
Output
(array(['fail', 'ok', 'warn'], dtype='<U4'), array([ 24, 7588, 452]))
matches the file: 8063 of 8064

np.unique(..., return_counts=True) returns the sorted distinct values and how often each one occurs. The rule matches 8,063 of 8,064 rows. The one difference is a warn row whose trigger value is a blank cell: NaN fails every comparison, so the rule says ok.

np.clip(a, low, high) limits values to a range. Values below low become low; values above high become high. Use it to cap outliers or to keep probabilities inside [0, 1].

print(np.clip(temperature[:6], 20.0, 22.5))
print(np.nanmax(np.clip(temperature, None, 30.0))) # cap only from above
Output
[20.21 22.3 20. 22.5 20.22 22.44]
30.0

Linear algebra is the math of vectors and matrices. A vector is a 1-dimensional array of numbers. Machine learning models are mostly linear algebra: a prediction is a weighted sum of features, and a weighted sum of many rows is a matrix product.

Matrix multiplication combines a matrix AA of shape (m,k)(m, k) with a matrix BB of shape (k,n)(k, n). The result CC has shape (m,n)(m, n). Each element is the dot product (the sum of element-wise products) of a row of AA and a column of BB:

Cij=∑p=1kAip BpjC_{ij} = \sum_{p=1}^{k} A_{ip} \, B_{pj}

In Python, the operator @ multiplies matrices. * multiplies element by element. The inner lengths must match: (m, k) @ (k, n).

The next matrix is the real number of units that the three North stores sold in 2024 of three products: Wireless Earbuds (P001, 79.99 USD), Noise-Cancelling Headphones (P002, 249.00 USD) and the 55-inch 4K Smart TV (P003, 1,299.00 USD).

units_2024 = np.array([
[101, 63, 31], # S01
[56, 34, 17], # S02
[42, 29, 11], # S03
])
print(units_2024 @ price) # (3, 3) @ (3,) -> (3,): revenue at list price
print(np.ones(3) @ units_2024) # (3,) @ (3, 3) -> (3,): units per product
print((units_2024 * price).round(2)) # element-wise: revenue per store and product
Output
[64034.99 35028.44 24869.58]
[199. 126. 59.]
[[ 8078.99 15687. 40269. ]
[ 4479.44 8466. 22083. ]
[ 3359.58 7221. 14289. ]]

units_2024 @ price computes, for each store, 101 × 79.99 + 63 × 249.00 + 31 × 1,299.00. That is list-price revenue before discounts: 64,034.99 USD for S01. A vector of ones on the left sums the columns. With *, broadcasting multiplies each column by its price but does not add them up.

A linear system asks the reverse question: which vector xx gives Ax=bAx = b? Suppose you know the units and the list-price revenue of each store, but not the prices. np.linalg.solve(A, b) finds them:

list_revenue = units_2024 @ price
found = np.linalg.solve(units_2024, list_revenue)
print(found)
print(np.allclose(found, price))
inverse = np.linalg.inv(units_2024)
print(np.allclose(inverse @ units_2024, np.eye(3)))
print(inverse @ list_revenue)
Output
[ 79.99 249. 1299. ]
True
True
[ 79.99 249. 1299. ]

The inverse A−1A^{-1} of a square matrix is the matrix with A−1A=IA^{-1}A = I, the identity. So x=A−1bx = A^{-1}b also solves the system. Prefer solve(): it is faster and more accurate, because it never forms the inverse. A matrix whose rows depend on each other (one row is a mix of the others) has no inverse. It is called singular, and solve and inv then raise LinAlgError: Singular matrix.

An eigenvector of a square matrix AA is a direction that AA only stretches: Av=λvAv = \lambda v. The stretch factor λ\lambda is its eigenvalue. For a correlation matrix (the table of correlations between every pair of columns), the eigenvectors are the directions in which the data varies most, and each eigenvalue says how much of the variation lies along its direction. This is the idea behind PCA (principal component analysis, module 39), which replaces many correlated columns by a few main directions.

Take three size columns of data/houses.csv: sqft, bedrooms and bathrooms. For a symmetric matrix (equal to its transpose), such as a correlation matrix, use np.linalg.eigh. It returns real eigenvalues in ascending order.

houses = np.genfromtxt(
"data/houses.csv", delimiter=",", skip_header=1, usecols=(2, 3, 4, 13)
)
size = houses[:, :3] # sqft, bedrooms, bathrooms
corr = np.corrcoef(size, rowvar=False) # columns are the variables
print(corr)
values, vectors = np.linalg.eigh(corr)
print(values)
print(values / values.sum())
print(vectors[:, -1]) # direction of the largest eigenvalue
print(np.allclose(corr @ vectors, vectors * values)) # A v = lambda v, all at once
Output
[[1. 0.851 0.845]
[0.851 1. 0.896]
[0.845 0.896 1. ]]
[0.104 0.168 2.728]
[0.035 0.056 0.909]
[-0.57 -0.582 -0.58 ]
True

np.corrcoef with rowvar=False treats each column as a variable. The three columns are strongly correlated (0.85 to 0.90). The largest eigenvalue, 2.728, holds 91% of the total (3.0). Its eigenvector weighs the three columns almost equally (the sign is arbitrary). The last line checks Av=λvAv = \lambda v for all three eigenvectors at once: the columns of vectors are the eigenvectors, and vectors * values broadcasts the (3,) eigenvalues so that each column is multiplied by its own λ\lambda. Meaning: the three columns mostly measure one thing, the size of the house. A model sees nearly the same information three times.

The singular value decomposition (SVD) writes any matrix MM, square or not, as a product of three matrices:

M=U Σ V⊤M = U \, \Sigma \, V^\top

The columns of UU are patterns over the rows (here: stores) and the rows of V⊤V^\top are patterns over the columns (here: quarters). Σ\Sigma is a diagonal matrix of singular values, sorted from largest to smallest. Each one measures how much of the matrix its pair of patterns explains. np.linalg.svd returns UU, the singular values as a vector, and V⊤V^\top:

U, s, Vt = np.linalg.svd(sales_q, full_matrices=False)
print(U.shape, s.shape, Vt.shape)
print(s)
print(s**2 / np.sum(s**2))
print(np.allclose(U @ np.diag(s) @ Vt, sales_q))
Output
(3, 3) (3,) (3, 4)
[149970.083 12497.475 5640.947]
[0.992 0.007 0.001]
True

The first singular value holds 99.2% of the sum of squares, which is the measure of “size” that the SVD splits up. So the sales matrix is almost one store pattern times one quarter pattern: each store has a size, and every store follows the same seasonal shape with a strong Q4. Example 6 applies this to the full 12 × 24 matrix.

Function Solves Notes
A @ B matrix product (m, k) @ (k, n) → (m, n)
np.linalg.solve(A, b) Ax=bAx = b for square AA prefer it to inv(A) @ b
np.linalg.inv(A) A−1A^{-1} rarely needed
np.linalg.lstsq(X, y) least squares for tall XX see Example 5
np.linalg.eigh(S) eigenvalues of a symmetric matrix real, ascending
np.linalg.eig(A) eigenvalues of any square matrix dtype depends on the version (complex on 2.5)
np.linalg.svd(M, full_matrices=False) M=UΣV⊤M = U \Sigma V^\top any shape; singular values descending
np.linalg.norm(v) length of a vector sqrt(sum(v**2))
np.linalg.det(A) determinant: one number computed from a square matrix 0 means singular

Simulations, train/test splits, bootstrapping and model initialization all need random numbers. Module 09 used the random module. NumPy’s random generator draws whole arrays at once. Create one with np.random.default_rng(seed). The same seed gives the same numbers on every run, so your results are reproducible: anyone who runs your code gets your numbers.

rng = np.random.default_rng(42)
print(rng.normal(loc=0.0, scale=0.1, size=4)) # sensor noise: mean 0, sd 0.1
print(rng.integers(1, 6, size=5)) # ratings 1-5 (the high end is excluded)
print(rng.random(3)) # floats in [0, 1)
print(rng.choice(["S1", "S2", "S3", "S4"], size=6)) # with replacement
print(rng.choice(10, size=3, replace=False)) # 3 distinct row positions
print(rng.permutation(6)) # a shuffled copy of 0..5
Output
[ 0.03 -0.104 0.075 0.094]
[2 1 3 5 4]
[0.786 0.128 0.45 ]
['S4' 'S3' 'S2' 'S1' 'S4' 'S4']
[8 5 3]
[1 0 4 3 5 2]
Method Draws
rng.normal(loc, scale, size) the bell-shaped normal distribution with mean loc and standard deviation scale
rng.integers(low, high, size) integers from low up to, but not including, high
rng.random(size) floats from 0 (included) to 1 (excluded)
rng.uniform(low, high, size) floats evenly spread between low and high
rng.choice(a, size, replace=True, p=None) items of a; replace=False for distinct items; p for weights
rng.permutation(a) a shuffled copy; rng.shuffle(a) shuffles in place
rng.poisson(lam, size) counts of events per interval, such as orders per hour

Each call moves the generator forward, so two calls give different numbers. Reproducibility comes from the seed and the order of the calls:

first = np.random.default_rng(42).normal(size=3)
again = np.random.default_rng(42).normal(size=3)
other = np.random.default_rng(7).normal(size=3)
print(np.array_equal(first, again), np.array_equal(first, other))
Output
True False

Older tutorials and Stack Overflow answers also use aliases that NumPy 2.0 removed. On NumPy 2 they raise AttributeError, and the message usually names the replacement:

print(np.NaN)
Output
AttributeError: `np.NaN` was removed in the NumPy 2.0 release. Use `np.nan` instead.
Removed Use instead
np.NaN, np.Inf np.nan, np.inf
np.float_, np.complex_ np.float64, np.complex128
np.product, np.cumproduct np.prod, np.cumprod
np.alltrue, np.sometrue np.all, np.any
np.round_ np.round
np.trapz np.trapezoid
np.in1d np.isin
np.row_stack np.vstack
np.asfarray(a) np.asarray(a, dtype=np.float64)
a.ptp() (method) np.ptp(a)

Example 1 — Summarize four sensors in one pass

Section titled “Example 1 — Summarize four sensors in one pass”

Goal: A facilities team monitors four sensors. Load the temperatures of data/sensors.csv, arrange them as a timestamp × sensor matrix and report the mean per sensor and the daily mean of the drifting sensor S3.

readings = np.genfromtxt(
"data/sensors.csv", delimiter=",", skip_header=1, usecols=(2, 3, 4)
)
ids = np.loadtxt("data/sensors.csv", delimiter=",", skiprows=1, usecols=1, dtype=str)
print(readings.shape, readings.dtype, f"{readings.nbytes:,} bytes")
print(ids[:8])
Output
(8064, 3) float64 193,536 bytes
['S1' 'S2' 'S3' 'S4' 'S1' 'S2' 'S3' 'S4']

8,064 rows × 3 float columns take 193,536 bytes. The sensor ids repeat S1 to S4, because the file is sorted by timestamp and then by sensor.

Step 2 — Check the layout before you reshape

Section titled “Step 2 — Check the layout before you reshape”
print(np.array_equal(ids.reshape(-1, 4)[:, 0], np.full(2016, "S1")))
print(np.all(ids.reshape(-1, 4) == np.array(["S1", "S2", "S3", "S4"])))
Output
True
True

A reshape trusts the order of the rows. If one row were missing, every row after it would shift into the wrong column, with no error. The second check compares the (2016, 4) id matrix with the (4,) row ["S1", "S2", "S3", "S4"] by broadcasting. All 8,064 ids are in place.

temp = readings[:, 0].reshape(-1, 4)
print(temp.shape)
print(temp[:3])
print("missing per sensor:", np.isnan(temp).sum(axis=0))
Output
(2016, 4)
[[20.21 22.3 19.4 24.52]
[20.22 22.44 19.46 24.63]
[20.16 22.25 19.54 24.73]]
missing per sensor: [6 4 6 6]

Each row is now one timestamp and each column one sensor. Missing values are counted per sensor with axis=0.

Step 4 — Compute the statistics per sensor

Section titled “Step 4 — Compute the statistics per sensor”
mean_c = np.nanmean(temp, axis=0)
low = np.nanmin(temp, axis=0)
high = np.nanmax(temp, axis=0)
for sensor, m, lo, hi in zip(["S1", "S2", "S3", "S4"], mean_c, low, high):
print(f"{sensor}: mean {m:.2f} °C, min {lo:.2f}, max {hi:.2f}")
Output
S1: mean 22.05 °C, min 18.62, max 38.63
S2: mean 24.60 °C, min 20.24, max 44.89
S3: mean 23.53 °C, min 18.56, max 41.66
S4: mean 26.04 °C, min 23.22, max 44.36

One call per statistic covers all four sensors. The only Python loop is the one that prints four lines. The maximum values near 40 °C or above are spikes; Example 2 finds them.

daily = np.nanmean(temp.reshape(14, 144, 4), axis=1) # (14 days, 4 sensors)
print(daily.shape)
print(daily[:, 2].round(2))
print(f"S3 change: {daily[-1, 2] - daily[0, 2]:+.2f} °C in 13 days")
Output
(14, 4)
[21.29 21.6 21.84 22.26 22.71 22.84 23.74 23.65 24.07 24.44 24.8 24.98
25.34 25.85]
S3 change: +4.55 °C in 13 days

The 3-dimensional reshape gives day, slot and sensor axes. Averaging over axis 1 (the 144 slots) leaves one mean per day and sensor. S3 rises from 21.29 °C to 25.85 °C: about 0.35 °C per day. This is calibration drift, a slow, steady error that builds up in a sensor, not a warmer room: the other three sensors stay flat.

Common mistakes:

  • Using mean() instead of nanmean(). The result is nan for every sensor with a gap.
  • Reshaping without checking the row order. Sort the data or verify the id pattern first, as in Step 2.
  • Averaging over the wrong axis. axis=0 in Step 5 would average over days and return a (144, 4) daily profile instead of a trend.

Example 2 — Flag temperature spikes with masks and broadcasting

Section titled “Example 2 — Flag temperature spikes with masks and broadcasting”

Goal: The data dictionary says that 40 temperature readings are spikes of +9 to +18 °C. Find them without a loop, list where they are, and check what they do to the averages.

Step 1 — Measure each reading against its sensor’s median

Section titled “Step 1 — Measure each reading against its sensor’s median”
median = np.nanmedian(temp, axis=0) # shape (4,): one median per sensor
deviation = temp - median # (2016, 4) - (4,)
print(median)
print(deviation[:3])
Output
[22.01 24.515 23.47 25.96 ]
[[-1.8 -2.215 -4.07 -1.44 ]
[-1.79 -2.075 -4.01 -1.33 ]
[-1.85 -2.265 -3.93 -1.23 ]]

Broadcasting subtracts each sensor’s median from its own column. The median (the middle value) is a robust baseline: 40 spikes barely move it. A mean would move toward the spikes.

spike = deviation > 5.0
print("spikes:", spike.sum())
print("per sensor:", spike.sum(axis=0))
Output
spikes: 40
per sensor: [ 8 13 11 8]

The daily cycle moves a reading by a few degrees around the median. A spike adds at least 9 °C. A threshold of 5 °C lies between the two, and it finds exactly the 40 spikes of the data dictionary. NaN deviations compare as False, so gaps are never flagged.

rows, cols = np.nonzero(spike)
stamps = timestamps.reshape(-1, 4)[:, 0] # one timestamp per row of temp
names = np.array(["S1", "S2", "S3", "S4"])
for r, c in zip(rows[:4], cols[:4]):
print(stamps[r], names[c], temp[r, c])
Output
2024-05-01T00:40:00 S2 38.03
2024-05-01T10:40:00 S3 33.51
2024-05-02T12:30:00 S1 36.03
2024-05-02T13:20:00 S2 44.89

np.nonzero(mask) returns one array of positions per axis: the rows and the columns of the True values. Fancy indexing with those positions gives the timestamps, the sensor names and the values.

mu = np.nanmean(temp, axis=0)
sigma = np.nanstd(temp, axis=0)
z_flag = np.abs((temp - mu) / sigma) > 4
print("z-score flags:", z_flag.sum(), "found spikes:", (z_flag & spike).sum())
Output
z-score flags: 36 found spikes: 36

A z-score rule with a threshold of 4 flags only 36 readings. The spikes inflate the standard deviation, and S3’s drift widens it further, so a few spikes look normal. The median rule is more reliable for this data.

Step 5 — Remove the spikes and recompute the means

Section titled “Step 5 — Remove the spikes and recompute the means”
clean_temp = temp.copy()
clean_temp[spike] = np.nan
before = np.nanmean(temp, axis=0)
after = np.nanmean(clean_temp, axis=0)
print("before:", before)
print("after: ", after)
print("change:", after - before)
Output
before: [22.051 24.602 23.529 26.038]
after: [21.999 24.519 23.46 25.986]
change: [-0.052 -0.082 -0.069 -0.053]

The masked assignment sets the 40 spikes to NaN in the copy; the original temp keeps them. The means drop by 0.05 to 0.08 °C. Small, but enough to shift a monthly report or a model’s input.

Common mistakes:

  • Writing clean_temp = temp and then clean_temp[spike] = np.nan. That is the same array, so the raw data is lost. Call .copy().
  • Using the mean and standard deviation of data that contains the outliers. The outliers distort both. Use the median, or a percentile.
  • Forgetting that np.nonzero returns a tuple of arrays, one per axis. On a 2-D mask, unpack two arrays.

Example 3 — Build a stores × months sales matrix

Section titled “Example 3 — Build a stores × months sales matrix”

Goal: Management wants a 12 × 24 matrix of revenue by store and month for 2023–2024, with store totals, monthly totals, each month’s share of its store and the growth from 2023 to 2024.

import csv
with open("data/sales.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
store_col = np.array([row["store_id"] for row in rows])
month_col = np.array([row["order_date"][:7] for row in rows]) # "2023-01"
revenue = np.array([float(row["revenue"]) for row in rows])
print(len(rows), store_col[:3], month_col[:3], revenue[:3])
print(f"total revenue: {revenue.sum():,.2f}")
Output
20228 ['S11' 'S10' 'S05'] ['2023-01' '2023-01' '2023-01'] [66.49 14.99 19.99]
total revenue: 3,596,523.83

The csv module reads mixed columns. Each list comprehension turns one column into an array. The total, 3,596,523.83 USD, matches the data dictionary.

Step 2 — Turn labels into row and column positions

Section titled “Step 2 — Turn labels into row and column positions”
store_names, store_pos = np.unique(store_col, return_inverse=True)
month_names, month_pos = np.unique(month_col, return_inverse=True)
print(store_names)
print(month_names[:3], month_names[-1], len(month_names))
print(store_pos[:3], month_pos[:3])
Output
['S01' 'S02' 'S03' 'S04' 'S05' 'S06' 'S07' 'S08' 'S09' 'S10' 'S11' 'S12']
['2023-01' '2023-02' '2023-03'] 2024-12 24
[10 9 4] [0 0 0]

np.unique(..., return_inverse=True) returns the sorted distinct labels and, for every row, the position of its label in that sorted list. Those positions are the row and column of each sales line in the matrix.

sales = np.zeros((len(store_names), len(month_names)))
np.add.at(sales, (store_pos, month_pos), revenue)
print(sales.shape)
print((sales[:3, :6] / 1000).round(1))
print(np.isclose(sales.sum(), revenue.sum()))
Output
(12, 24)
[[ 8.2 7.3 9.8 12.6 19.9 12.1]
[ 5.7 4.4 6.7 3.8 15.3 13.2]
[ 4.4 7.2 5.9 4.5 4.1 7.3]]
True

np.add.at(target, positions, values) adds each value to its cell, and it handles repeated positions correctly: thousands of lines fall in the same store and month. The shortcut sales[store_pos, month_pos] += revenue is wrong here. It applies only one line per cell, because fancy-index assignment does not accumulate.

store_total = sales.sum(axis=1)
month_total = sales.sum(axis=0)
best = month_names[sales.argmax(axis=1)]
print((store_total / 1000).round(1))
print(month_names[month_total.argmin()], f"{month_total.min():,.0f}")
print(month_names[month_total.argmax()], f"{month_total.max():,.0f}")
print(dict(zip(store_names[:4].tolist(), best[:4].tolist())))
Output
[406.5 268.5 213.2 395.5 300.3 196. 468.3 280.7 244.7 401.4 268.8 152.7]
2023-02 77,405
2024-12 302,912
{'S01': '2024-12', 'S02': '2024-12', 'S03': '2023-12', 'S04': '2024-12'}

axis=1 gives one total per store and axis=0 one per month. February 2023 is the weakest month and December 2024 the strongest, as the data dictionary says. Fancy indexing turns the argmax positions into month labels. .tolist() converts NumPy strings to plain Python strings, so the dict prints cleanly.

Step 5 — Compute shares and growth with broadcasting

Section titled “Step 5 — Compute shares and growth with broadcasting”
share = sales / sales.sum(axis=1, keepdims=True) # (12, 24) / (12, 1)
print(share[0, -1].round(4), np.allclose(share.sum(axis=1), 1))
by_year = sales.reshape(12, 2, 12).sum(axis=2) # store, year
growth = by_year[:, 1] / by_year[:, 0] - 1
for name, g in zip(store_names[:3], growth[:3]):
print(f"{name}: {g:+.1%}")
Output
0.0994 True
S01: +19.0%
S02: +11.6%
S03: +17.6%

December 2024 is 9.94% of S01’s two-year revenue. The reshape (12, 2, 12) splits the 24 months into 2 years of 12, because the months are in order. Summing over the last axis gives one total per store and year.

Step 6 — Handle the store that opened late

Section titled “Step 6 — Handle the store that opened late”
open_months = sales > 0
print("months with sales:", open_months.sum(axis=1))
print(month_names[~open_months[11]])
monthly_avg = sales.sum(axis=1) / open_months.sum(axis=1)
print(f"S12 average per open month: {monthly_avg[11]:,.0f}")
print(f"S12 average over 24 months: {sales[11].mean():,.0f}")
Output
months with sales: [24 24 24 24 24 24 24 24 24 24 24 19]
['2023-01' '2023-02' '2023-03' '2023-04' '2023-05']
S12 average per open month: 8,035
S12 average over 24 months: 6,361

S12 (Denver) opened on 2023-06-15, so its first five months are 0. Dividing by 24 months would make the store look weaker than it is. A mask of open months gives a fair average.

Common mistakes:

  • Using sales[i, j] += value with repeated fancy positions. Use np.add.at or np.bincount.
  • Dividing a (12, 24) matrix by a (12,) vector of totals. Use keepdims=True.
  • Treating 0 as a real value. Zero revenue before a store opens is “no data”, not “bad month”.

Example 4 — Vectorize a revenue and profit loop

Section titled “Example 4 — Vectorize a revenue and profit loop”

Goal: A legacy script computes the revenue and gross profit of every sales line with a Python loop. Replace the loop with array operations, check that the results are the same, and measure the speed-up.

cost_by_product = {}
with open("data/products.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
cost_by_product[row["product_id"]] = float(row["unit_cost"])
def profit_loop(rows: list[dict[str, str]]) -> float:
total = 0.0
for row in rows:
qty = int(row["quantity"])
net = float(row["unit_price"]) * qty * (1 - float(row["discount"]))
total += net - cost_by_product[row["product_id"]] * qty
return total
print(f"gross profit (loop): {profit_loop(rows):,.2f}")
Output
gross profit (loop): 1,760,141.29

The loop parses three fields, looks up the cost and adds one line at a time: 20,228 Python iterations. It uses the unrounded revenue of each line. The data dictionary’s gross profit, 1,760,135.83 USD, uses the rounded revenue column, so the two differ by about 5 USD of rounding.

price_col = np.array([float(row["unit_price"]) for row in rows])
qty_col = np.array([int(row["quantity"]) for row in rows])
disc_col = np.array([float(row["discount"]) for row in rows])
product_names, product_pos = np.unique(
np.array([row["product_id"] for row in rows]), return_inverse=True
)
cost_table = np.array([cost_by_product[p] for p in product_names])
print(qty_col.dtype, product_names[:3], cost_table[:3])
Output
int64 ['P001' 'P002' 'P003'] [ 31.5 104. 845. ]

Parsing still happens once in Python. After that, every calculation works on arrays. cost_table is a lookup table: position k holds the unit cost of product product_names[k].

Step 3 — Compute revenue and profit in one expression each

Section titled “Step 3 — Compute revenue and profit in one expression each”
net = price_col * qty_col * (1 - disc_col)
cost = cost_table[product_pos] * qty_col # fancy indexing as a lookup
profit = net - cost
print(f"gross profit (NumPy): {profit.sum():,.2f}")
print(np.isclose(profit.sum(), profit_loop(rows)))
print(np.abs(np.round(net, 2) - revenue).max() <= 0.01 + 1e-9)
Output
gross profit (NumPy): 1,760,141.29
True
True

cost_table[product_pos] turns 20,228 product positions into 20,228 unit costs in one step. Both versions agree. Rounded to cents, the NumPy revenue differs from the file’s revenue column by at most one cent, the tolerance the data dictionary asks for. The check uses the maximum absolute difference, because np.allclose would also add a relative tolerance.

t_loop = timeit.timeit(lambda: profit_loop(rows), number=5) / 5
def profit_numpy() -> float:
net = price_col * qty_col * (1 - disc_col)
return float((net - cost_table[product_pos] * qty_col).sum())
t_numpy = timeit.timeit(profit_numpy, number=5) / 5
print(f"loop: {t_loop * 1000:.2f} ms")
print(f"NumPy: {t_numpy * 1000:.2f} ms")
print("NumPy at least 10x faster:", t_numpy * 10 < t_loop)
Output
loop: 3.65 ms
NumPy: 0.05 ms
NumPy at least 10x faster: True

The loop parses strings on every call; the NumPy version works on columns that are already parsed. That is the real lesson: parse once into arrays, then compute many times. The times are masked on this page because they change from machine to machine.

Common mistakes:

  • Timing only the arithmetic and forgetting the parsing. Measure what your program really does.
  • Comparing float totals with ==. Use np.isclose and np.allclose.
  • Keeping a dict lookup inside the vectorized code ([cost_by_product[p] for p in ...] on every call). Build the lookup array once.

Example 5 — Fit a least-squares line for house prices

Section titled “Example 5 — Fit a least-squares line for house prices”

Goal: An estate agent wants a quick rule of thumb: how much does each extra square foot add to the price? Fit the line price = a + b × sqft to the 3,000 sales of data/houses.csv with linear algebra.

sqft = houses[:, 0]
price_usd = houses[:, 3]
print(houses.shape, np.isnan(houses).sum())
print(sqft[:3], price_usd[:3])
Output
(3000, 4) 0
[2420. 1610. 1260.] [1097500. 486500. 223000.]

The concepts section loaded sqft, bedrooms, bathrooms and price into houses. These four columns have no blanks.

X = np.column_stack([np.ones_like(sqft), sqft])
print(X.shape)
print(X[:3])
Output
(3000, 2)
[[ 1. 2420.]
[ 1. 1610.]
[ 1. 1260.]]

A design matrix has one row per observation and one column per input of the model. The column of ones lets the model learn the intercept aa. Then each prediction is a dot product: y^i=a⋅1+b⋅sqfti\hat{y}_i = a \cdot 1 + b \cdot \text{sqft}_i, so all predictions together are XβX\beta with β=(a,b)\beta = (a, b).

Least squares picks the β\beta that makes the sum of squared errors ∥y−Xβ∥2\lVert y - X\beta \rVert^2 as small as possible. Setting its gradient to zero gives the normal equations:

X⊤X β=X⊤yX^\top X \, \beta = X^\top y

X⊤XX^\top X is a small 2 × 2 matrix, so solve handles it directly:

beta = np.linalg.solve(X.T @ X, X.T @ price_usd)
a, b = beta
print(f"intercept: {a:,.0f} USD, slope: {b:,.2f} USD per sqft")
Output
intercept: -130,345 USD, slope: 326.83 USD per sqft

Each extra square foot adds about 327 USD. The intercept is negative: a 0-sqft house would cost −130,345 USD. That is not a real price. The line only makes sense inside the range of the data (550 to 5,710 sqft).

beta_lstsq, residual_ss, rank, singular = np.linalg.lstsq(X, price_usd)
print(beta_lstsq, rank)
print(np.allclose(beta, beta_lstsq))
print(f"condition number of X.T @ X: {np.linalg.cond(X.T @ X):.2e}")
Output
[-130345.098 326.833] 2
True
condition number of X.T @ X: 3.09e+07

np.linalg.lstsq(X, y) solves the least-squares problem directly from XX, with an SVD. Both methods agree here. The condition number measures how much rounding errors can grow in a solve; 3 × 10⁷ is large. Forming X⊤XX^\top X squares the condition number of XX, so with many correlated features the normal equations lose precision first. Prefer lstsq in real code. Standardizing the columns (as in the broadcasting section) also helps.

predicted = X @ beta
residuals = price_usd - predicted
r2 = 1 - np.sum(residuals**2) / np.sum((price_usd - price_usd.mean()) ** 2)
print(f"R^2: {r2:.3f}")
print(f"RMSE: {np.sqrt(np.mean(residuals**2)):,.0f} USD")
new_sizes = np.array([1200, 2000, 3000])
print(np.column_stack([np.ones(3), new_sizes]) @ beta)
Output
R^2: 0.533
RMSE: 217,812 USD
[261854.803 523321.404 850154.656]

A residual is the true value minus the prediction. R2R^2 (the coefficient of determination) is the share of the variation in price that the model explains: 1 is perfect, 0 is no better than the mean. Size alone explains 53% of the price. The RMSE (root mean squared error) is the typical error in USD. Module 35 adds the other features, the neighborhood and a log transform, which raise R2R^2 to about 0.9.

Common mistakes:

  • Forgetting the column of ones. The line is then forced through the origin.
  • Using np.linalg.inv(X.T @ X) @ X.T @ y. It works on small, clean data and loses precision on real data. Use lstsq.
  • Reading the intercept as a real price. Interpret a model only inside the range of its data.

Example 6 — Find the shared seasonal pattern with SVD

Section titled “Example 6 — Find the shared seasonal pattern with SVD”

Goal: The 12 × 24 sales matrix of Example 3 has 288 numbers. Find out how much of it one “store size × seasonal pattern” explains, and which store-month deviates most from that pattern.

U, s, Vt = np.linalg.svd(sales, full_matrices=False)
print(U.shape, s.shape, Vt.shape)
print((s / 1000).round(1))
print((s**2 / np.sum(s**2))[:3].round(3))
Output
(12, 12) (12,) (12, 24)
[235.2 25.6 21. 18.6 17.5 15.9 15. 12.4 10.8 10. 7.5 3.7]
[0.954 0.011 0.008]

The first singular value is 9 times larger than the second. It alone holds 95.4% of the sum of squares. The matrix is nearly rank 1: close to one column vector times one row vector.

store_score = -U[:, 0] * s[0] # flip the sign: SVD signs are arbitrary
season = -Vt[0]
print((store_score / 1000).round(1))
print((season / season.mean()).round(2)[-12:])
Output
[ 89.4 58.9 45.1 84.8 63.1 43.2 102.6 61.2 53.6 84.9 58.1 32.9]
[0.74 0.71 0.98 0.79 0.84 1.03 0.98 1.03 0.97 1.11 1.78 2.05]

The SVD can return a pattern and its negative; flipping both signs gives the same product. The store scores rank the stores by size: S07 (New York) highest, S12 (Denver) lowest. The seasonal pattern, scaled to an average of 1, shows the November and December peak of 2024 (1.78 and 2.05 times an average month).

Step 3 — Rebuild the matrix from the first pattern

Section titled “Step 3 — Rebuild the matrix from the first pattern”
rank1 = s[0] * np.outer(U[:, 0], Vt[0]) # (12, 1) times (1, 24)
print(rank1.shape)
print((rank1[:2, -3:] / 1000).round(1))
print((sales[:2, -3:] / 1000).round(1))
Output
(12, 24)
[[19.1 30.6 35.3]
[12.6 20.2 23.3]]
[[15.5 26.5 40.4]
[14.6 21.2 23.1]]

np.outer(u, v) builds the matrix of all products u[i] * v[j], the same as broadcasting u[:, np.newaxis] * v. This rank-1 approximation stores 12 + 24 = 36 numbers instead of 288 and already comes close to the real values.

surprise = sales - rank1
i, j = np.unravel_index(np.abs(surprise).argmax(), surprise.shape)
print(store_names[i], month_names[j])
print(f"actual {sales[i, j]:,.0f}, pattern {rank1[i, j]:,.0f}")
Output
S10 2023-03
actual 22,247, pattern 12,349

argmax on a 2-D array returns a position in the flattened array. np.unravel_index turns it back into a (row, column) pair. S10 (Seattle) sold 22,247 USD in March 2023, almost twice what its pattern predicts: a store-month worth a closer look. The same idea, “subtract the main pattern and look at what is left”, drives recommendation systems and anomaly detection.

Common mistakes:

  • Calling svd without full_matrices=False on a tall or wide matrix. U is then a 12 × 12 and Vt a 24 × 24 matrix, and U @ np.diag(s) @ Vt fails.
  • Interpreting the sign of a singular vector. Only the product of the two signs has a meaning.
  • Reading singular values as shares. Square them first: the squares add up to the total sum of squares.

Example 7 — Split, fit and bootstrap with a seeded generator

Section titled “Example 7 — Split, fit and bootstrap with a seeded generator”

Goal: Check how reliable the slope of Example 5 is. Split the houses into training and test rows with a random permutation, evaluate the line on the test rows, and estimate a 95% interval for the slope with the bootstrap (resampling the rows with replacement many times).

rng = np.random.default_rng(42)
order = rng.permutation(len(price_usd))
train_idx, test_idx = order[:2250], order[2250:]
print(order[:6], len(train_idx), len(test_idx))
print(np.intersect1d(train_idx, test_idx).size)
Output
[2342 554 1243 780 2142 2911] 2250 750
0

rng.permutation(n) shuffles the positions 0 to n − 1. The first 75% become training rows and the rest test rows. np.intersect1d finds no common position, so no house is in both sets.

coef_train = np.linalg.lstsq(X[train_idx], price_usd[train_idx])[0]
test_error = price_usd[test_idx] - X[test_idx] @ coef_train
test_r2 = 1 - np.sum(test_error**2) / np.sum(
(price_usd[test_idx] - price_usd[test_idx].mean()) ** 2
)
print(coef_train.round(2), f"test R^2: {test_r2:.3f}")
Output
[-132867.61 328.48] test R^2: 0.526

Fancy indexing with the position arrays selects the rows of X and price_usd together, so they stay aligned. The test R2R^2 measures the fit on houses the model has not seen. Module 34 does this with train_test_split.

n = len(price_usd)
slopes = np.empty(1000)
for k in range(1000):
pick = rng.integers(0, n, size=n) # n row positions, with replacement
slopes[k] = np.linalg.lstsq(X[pick], price_usd[pick])[0][1]
low_q, high_q = np.percentile(slopes, [2.5, 97.5])
print(f"slope 95% interval: {low_q:.1f} to {high_q:.1f} USD per sqft")
Output
slope 95% interval: 304.9 to 348.8 USD per sqft

Each resample draws 3,000 row positions with replacement, so some houses appear twice and others not at all. The spread of the 1,000 slopes shows how much the slope would vary with other samples of houses. The loop runs 1,000 times, but each step is a vectorized least-squares fit on 3,000 rows.

Step 4 — Confirm that the result is reproducible

Section titled “Step 4 — Confirm that the result is reproducible”
def bootstrap_interval(seed: int, rounds: int = 200) -> np.ndarray:
gen = np.random.default_rng(seed)
picks = gen.integers(0, n, size=(rounds, n)) # all resamples at once
est = [np.linalg.lstsq(X[p], price_usd[p])[0][1] for p in picks]
return np.percentile(est, [2.5, 97.5])
print(bootstrap_interval(42).round(1), bootstrap_interval(42).round(1))
print(bootstrap_interval(7).round(1))
Output
[307. 344.3] [307. 344.3]
[305.6 350.7]

The same seed gives the same interval, digit for digit. Another seed gives a slightly different interval, which is the random error of the bootstrap itself. integers(..., size=(rounds, n)) draws all positions in one call: each row of picks is one resample.

Common mistakes:

  • Shuffling X and price_usd with two separate permutation calls. The rows no longer match. Shuffle one array of positions and index both.
  • Creating a new generator with the same seed inside the loop. Every resample is then identical.
  • Using np.random.seed() and global functions. Pass a Generator around instead.
Mistake Symptom Fix
and, or, not on arrays ValueError: The truth value of an array with more than one element is ambiguous Use &, |, ~ with parentheses
a >= 33 & b without parentheses Thousands of wrong matches, no error (a >= 33) & b
Changing a slice The original array changes too .copy() the slice first
x == np.nan Always False np.isnan(x)
mean() on data with gaps nan np.nanmean()
Small integer dtype in arithmetic Silent wraparound: 100 + 100 gives -56 in int8 astype(np.int64) first
(n, m) divided by (n,) ValueError: operands could not be broadcast together keepdims=True or [:, np.newaxis]
a[[0, 1], [2, 3]] for a block Two elements instead of a 2 × 2 block a[np.ix_([0, 1], [2, 3])]
a[idx] += v with repeated idx Each position is added only once np.add.at(a, idx, v) or np.bincount
astype(int) on floats Values truncated: 2.7 becomes 2 np.round(a).astype(int)
np.std(a) against pandas .std() Slightly different numbers np.std(a, ddof=1)
np.linalg.inv(A) @ b Slower, less accurate np.linalg.solve(A, b)
Normal equations on many correlated features Unstable coefficients np.linalg.lstsq(X, y)
np.linalg.eig on a covariance matrix Complex dtype, unsorted values np.linalg.eigh
np.random.seed() and np.random.rand() Hidden global state, hard to reproduce rng = np.random.default_rng(42)
repr() or a list of NumPy scalars np.float64(20.21) in the output print(x), float(x) or .tolist()
  • Images and video: a photo is an array of shape (height, width, 3). Cropping is slicing, brightening is broadcasting and a mask selects a region. Pillow and OpenCV hand their images to NumPy.
  • Audio and signals: a sound file is a 1-D array of samples. Volume is multiplication, mixing is addition and np.fft finds the frequencies.
  • Games and graphics: positions and velocities of thousands of objects update with one vectorized step per frame. Rotations are 2 × 2 or 3 × 3 matrix products.
  • Engineering and finance tools: solving linear systems (circuits, structures) and simulating many random scenarios with a seeded generator (a Monte Carlo simulation, for example of portfolio risk) are everyday NumPy jobs.
  • An ndarray holds elements of one dtype in one block of memory. Operations on it run in C, element by element, with no Python loop.
  • shape, ndim, dtype, itemsize and nbytes describe an array. Choose the dtype on purpose: small integers overflow silently, and astype always makes a new array.
  • Basic slicing gives a view; masks and fancy indexing give a copy. Use np.shares_memory to check and .copy() to be safe.
  • Boolean masks filter and count. Combine them with &, |, ~ and parentheses.
  • Broadcasting aligns shapes from the right; length-1 axes stretch. keepdims=True keeps a reduced axis for the next step.
  • Aggregations take an axis: the named axis disappears. NaN-aware versions (nanmean, nanmax and so on) skip missing values.
  • reshape, concatenate, stack and split change the layout without loops. where, select and clip replace if statements.
  • @ multiplies matrices. Use solve for square systems, lstsq for least squares, eigh for symmetric matrices and svd to find the main patterns of any matrix.
  • np.random.default_rng(42) makes random numbers reproducible. Pass the generator to the code that needs it.

Q1. Why is temps * 2 on an array of 1 million floats much faster than a list comprehension?

Answer

The array stores raw float64 values in one block of memory and has one dtype. NumPy runs one compiled C loop over that block. The comprehension handles 1 million separate Python float objects, checking types and creating a new object for every result.

Q2. An array has shape (2016, 4). What are the shapes of a.sum(axis=0), a.sum(axis=1) and a.sum(axis=0, keepdims=True)?

Answer

(4,), (2016,) and (1, 4). The named axis disappears, or keeps length 1 with keepdims=True.

Q3. v = a[10:20], then v[0] = 0. Does a change? And with v = a[a > 5]?

Answer

With the slice, yes: a basic slice is a view on the same memory, so a[10] becomes 0. With the mask, no: boolean indexing returns a copy. np.shares_memory(v, a) tells you which case you have.

Q4. Can NumPy compute (12, 24) + (24,)? (12, 24) + (12,)? (12, 1) + (24,)? Give the result shapes.

Answer

(12, 24): the row of 24 repeats for every row. (12, 24) + (12,) fails: aligned from the right, 24 and 12 differ and neither is 1. (12, 1) + (24,) gives (12, 24): both arrays stretch, which makes an outer table.

Q5. What does np.array([100, 120], dtype=np.int8) * 2 return, and why?

Answer

[-56 -16]. 200 and 240 do not fit in int8 (maximum 127), so they wrap around by 256 with no warning. Convert to int64 first.

Q6. Why is x == np.nan useless, and what do you write instead?

Answer

NaN is not equal to anything, not even to itself, so the comparison is False everywhere. Use np.isnan(x). To skip gaps in a statistic, use the nan functions such as np.nanmean(x).

Q7. What is the difference between A * B and A @ B for two (3, 3) arrays?

Answer

A * B multiplies element by element: C[i, j] = A[i, j] * B[i, j]. A @ B is the matrix product: C[i, j] is the dot product of row i of A and column j of B.

Q8. Why should you prefer np.linalg.solve(A, b) to np.linalg.inv(A) @ b, and lstsq to the normal equations?

Answer

solve never forms the inverse, so it is faster and has smaller rounding errors. The normal equations use X⊤XX^\top X, which squares the condition number of XX and loses precision with correlated features. lstsq works on XX directly.

Q9. The first singular value of a sales matrix holds 95% of its sum of squares. What does that tell you?

Answer

The matrix is close to rank 1: one vector of store sizes times one seasonal pattern rebuilds most of it. The stores differ mainly in size and follow nearly the same monthly shape.

Q10. Two runs of your simulation give different results although you call np.random.default_rng(42). Name two possible causes.

Answer

The code creates the generator in one place but also calls the legacy global functions (np.random.rand()) somewhere else. Or the order or number of calls changed between runs, for example a new draw added before the simulation, which moves the generator to a different point. A third cause: a library uses its own unseeded randomness; pass it the generator or a random_state.

Q11. You need the 3 stores with the highest revenue from totals and the matching names from names. How?

Answer

top = np.argsort(totals)[::-1][:3], then names[top] and totals[top]. Fancy indexing with the same positions keeps the names and the values aligned.

Your progress

0 / 4 done

  • Exercises: 28 exercises with hints and full solutions, from warm-up to challenge.
  • Mini-project: a sensor health report built with arrays only.
  • Cheat sheet: creation, dtypes, indexing, broadcasting, aggregation, linear algebra and random numbers on one page.
  • Next module: 24. pandas fundamentals puts labels on NumPy arrays: Series, DataFrames and fast file I/O.