NumPy gives Python fast n-dimensional arrays of one dtype. This page is a reference for NumPy 2.x: how to build, index, combine and reduce arrays, and the rules that cause most bugs (dtype promotion, views, broadcasting). Every block runs in order and shares the setup below.
np.set_printoptions( precision = 3 , suppress = True ) # display only; values unchanged
m = np.arange( 12 ).reshape( 3 , 4 ) # a small 3 x 4 integer matrix
temps = np.array([ 20.2 , 22.3 , np.nan, 24.5 , 38.0 ])
I want to…
Use…
Example
make an array from a list
np.array(seq, dtype=...)
np.array([1, 2], dtype=np.float32)
wrap data without a copy if possible
np.asarray(x)
accepts lists, arrays, pandas columns
make evenly spaced numbers
np.arange, np.linspace
np.linspace(0, 1, 5)
make a filled array
np.zeros, np.ones, np.full, *_like
np.full((2, 3), np.nan)
make a coordinate grid
np.meshgrid(x, y), np.indices
xx, yy = np.meshgrid(x, y)
see the size and type
.shape, .ndim, .size, .dtype, .nbytes
m.shape → (3, 4)
convert the dtype
a.astype(dtype)
a.astype(np.int32)
predict a result dtype
np.result_type(a, b)
np.result_type(np.int8, np.uint8)
take a row, column or block
a[i], a[:, j], a[r0:r1, c0:c1]
m[:, 1]
keep values that pass a test
a boolean mask
a[(a > 0) & (a < 9)]
pick rows in a given order
fancy indexing
m[[2, 0]]
pick a block from row and column lists
np.ix_(rows, cols)
m[np.ix_([0, 2], [1, 3])]
check if two arrays share memory
np.shares_memory(a, b)
views share, copies do not
get an independent copy
a.copy()
before you edit a slice
combine shapes (n, 1) and (1, k)
broadcasting
col[:, None] * row
keep a reduced axis
keepdims=True
a / a.sum(axis=1, keepdims=True)
sum per column / per row
axis=0 / axis=1
m.sum(axis=0)
find the position of the max
argmax, then np.unravel_index
np.unravel_index(m.argmax(), m.shape)
ignore NaN in a statistic
np.nanmean, np.nanmax, …
np.nanmean(temps)
vectorized if/else
np.where(cond, a, b)
np.where(t > 30, "hot", "ok")
vectorized if/elif/else
np.select(conds, choices, default)
first true condition wins
put values into bins
np.digitize(x, edges)
np.digitize(t, [25, 35])
sort, or get the sort order
np.sort, np.argsort
np.argsort(-x)[:3]
top k without a full sort
np.argpartition
np.argpartition(x, -3)[-3:]
distinct values and counts
np.unique(a, return_counts=True)
test membership
np.isin(a, values)
replaces np.in1d
change the shape
.reshape, .ravel, .T
a.reshape(-1, 4)
add or drop a length-1 axis
a[:, None], np.expand_dims, np.squeeze
join arrays
np.concatenate, np.stack, np.column_stack
np.stack([a, b], axis=1)
split an array
np.split, np.array_split
np.array_split(a, 3)
matrix product
A @ B
* is element-wise
solve Ax = b
np.linalg.solve(A, b)
not inv(A) @ b
fit a least-squares line
np.linalg.lstsq(X, y)
coef = lstsq(X, y)[0]
eigenvalues of a symmetric matrix
np.linalg.eigh(S)
real, ascending
reproducible random numbers
rng = np.random.default_rng(42)
rng.normal(0, 1, 3)
compare float arrays
np.allclose, np.isclose
not ==
compare arrays exactly
np.array_equal(a, b, equal_nan=True)
get plain Python values
.item(), .tolist(), float(x)
for JSON and clean printing
save and load arrays
np.save, np.load, np.savez_compressed
.npy keeps shape and dtype
Call
Result
Note
np.array([[1, 2], [3, 4]])
2 × 2 int64
nested lists → axes
np.array([1, 2.5])
float64
one float upcasts all
np.asarray(x)
x itself if already a matching array
no copy when possible
np.zeros((2, 3)), np.ones(3)
float64 0.0 / 1.0
pass dtype= for others
np.full(shape, value)
filled with a value
np.full(3, np.nan)
np.empty(n)
uninitialized memory
fill it before you read it
np.zeros_like(a), np.full_like(a, 7)
same shape and dtype as a
np.arange(start, stop, step)
stop excluded
float steps can miss the end
np.linspace(a, b, n)
n points, both ends included
endpoint=False to drop b
np.logspace(0, 3, 4)
1, 10, 100, 1000
log-scale grids
np.eye(n), np.identity(n)
identity matrix
np.diag(v) / np.diag(M)
diagonal matrix / the diagonal
np.tile(a, reps), np.repeat(a, k)
repeat the whole / each element
np.meshgrid(x, y)
2-D coordinate arrays
indexing="ij" for matrix order
np.fromfunction(f, shape)
f(i, j) for every index
f gets whole index arrays
print (np.arange( 0 , 1 , 0.25 ), np.linspace( 0 , 1 , 5 ))
print (np.tile([ 1 , 2 ], 2 ), np.repeat([ 1 , 2 ], 2 ))
xx, yy = np.meshgrid(np.arange( 3 ), np.arange( 2 )) # xx varies along columns
print (np.fromfunction( lambda i, j: i * 10 + j, ( 2 , 3 ), dtype = int ))
print (m.shape, m.ndim, m.size, m.dtype, m.itemsize, m.nbytes, len (m))
[0. 0.25 0.5 0.75] [0. 0.25 0.5 0.75 1. ]
dtype
Bytes
Range / precision
Typical use
bool
1
True / False
masks; sum() counts True
int8 / uint8
1
−128..127 / 0..255
images, small codes
int16 / int32
2 / 4
±32,767 / ±2.1 × 10⁹
compact integers
int64
8
±9.2 × 10¹⁸
default integer (Linux, macOS, Windows on NumPy 2)
float32
4
~7 significant digits
deep learning, GPU
float64
8
~15–17 significant digits
default float
complex128
16
two float64
FFT, eig results
<U10
40
text up to 10 characters
4 bytes per character
datetime64[D], timedelta64[s]
8
dates, durations
np.datetime64("2024-05-01")
object
8
any Python object
slow, avoid
NumPy 2 decides the result dtype from the dtypes , never from the values. Python int, float and complex are “weak”: they take the array’s dtype when the kind fits. NumPy scalars such as np.float64(1) are “strong” and count like arrays.
Expression
Result dtype
Why
int8_array + 5
int8
weak Python int takes the array dtype
int8_array + 300
OverflowError
300 does not fit int8
int8_array + 5.0
float64
a Python float with an int array → default float
float32_array * 2.0
float32
weak Python float keeps float32
float32_array + np.float64(1)
float64
NumPy 2 change: NumPy scalars are strong (was float32)
int8_array + int16_array
int16
smallest type that holds both
int8_array + uint8_array
int16
signed and unsigned → wider signed
int64_array + float32_array
float64
float32 cannot hold every int64
int_array / int_array
float64
true division; // stays integer
np.float32(3) + 3.0
float32
scalar with weak Python float
i8 = np.array([ 100 , 120 ], dtype = np.int8)
f32 = np.array([ 1.5 ], dtype = np.float32)
print ((i8 + 5 ).dtype, (i8 + 5.0 ).dtype, (f32 * 2.0 ).dtype, (f32 + np.float64( 1 )).dtype)
print (i8 + i8) # wraps around silently
print (i8.astype(np.int64) + i8) # upcast first
print (np.result_type(np.int8, np.uint8), np.result_type(np.int64, np.float32))
print (np.iinfo(np.int8).max, np.finfo(np.float32).eps)
print (np.array([ 2.7 , - 2.7 ]).astype( int )) # truncates toward zero
print (np.round([ 0.5 , 1.5 , 2.5 ])) # rounds half to even
print (np.can_cast(np.int64, np.float64), np.can_cast(np.float64, np.int64))
int8 float64 float32 float64
bad = np.array([ 1 , 2 ], dtype = np.int8) + 300 # the Python int does not fit int8
OverflowError: Python integer 300 out of bounds for int8
Helper
Does
a.astype(t)
always a new array (pass copy=False to skip a no-op copy)
np.result_type(*arrays_or_dtypes)
the dtype an operation would give
np.can_cast(from, to)
is the cast “safe” (no loss)?
np.iinfo(t), np.finfo(t)
integer limits; float eps, max, tiny
np.isdtype(t, "real floating")
dtype kind test ("integral", "numeric", "bool")
np.issubdtype(a.dtype, np.floating)
older kind test, still valid
Index
Shape from (3, 4)
Returns
a[1, 2]
()
one element (a NumPy scalar)
a[1], a[1, :]
(4,)
a row, view
a[:, 2]
(3,)
a column, view
a[:, 2:3], a[:, [2]]
(3, 1)
a column that keeps its axis
a[:2, 1:]
(2, 3)
a block, view
a[::-1], a[:, ::2]
(3, 4), (3, 2)
reversed, every second, view
a[..., 0]
(3,)
... means all earlier axes
a[:, None, :], a[:, np.newaxis]
(3, 1, 4)
a new length-1 axis, view
a[a > 5]
(n,)
a boolean mask, 1-D copy
a[[2, 0]]
(2, 4)
fancy indexing, copy
a[[0, 2], [1, 3]]
(2,)
pairs (0, 1) and (2, 3), copy
a[np.ix_([0, 2], [1, 3])]
(2, 2)
the block of those rows and columns
print (m[ 1 , 2 ], m[ - 1 , - 1 ], m[ 1 ], m[:, 2 ])
print (m[m % 5 == 0 ], m[[ 2 , 0 ], 0 ], m[[ 0 , 2 ], [ 1 , 3 ]])
print (m[np.ix_([ 0 , 2 ], [ 1 , 3 ])])
t = np.array([ 22.0 , 34.0 , 25.0 , 43.0 ])
print (t[(t > 24 ) & (t < 40 )], t[ ~ (t > 30 )], np.isin(t, [ 25.0 , 43.0 ]))
print (np.nonzero(t > 30 ), np.flatnonzero(m > 9 ), np.argwhere(m > 9 ).tolist())
[34. 25.] [22. 25.] [False False True True]
(array([1, 3]),) [10 11] [[2, 2], [2, 3]]
Assignment works through every index kind and changes the array in place:
g = np.zeros(( 3 , 4 ), dtype = int )
g[ 0 ] = 1 # broadcast a scalar to a row
g[:, - 1 ] = [ 7 , 8 , 9 ] # a column from a list
g[[ 1 , 2 ], [ 0 , 1 ]] = 5 # two single cells
counts = np.zeros( 3 , dtype = int )
idx = np.array([ 0 , 0 , 2 ])
counts[idx] += 1 # buffered: index 0 counts once
print (counts, np.bincount(idx, minlength = 3 ))
np.add.at(counts, idx, 1 ) # unbuffered: every repeat counts
A view is a new array object over the same memory. Writing to a view changes the original.
Gives a view
Gives a copy
basic slices a[1:3], a[:, 0], a[::2]
boolean masks a[mask]
a.T, a.transpose(), a.swapaxes()
fancy indexing a[[0, 2]]
a.reshape(...) when the memory layout allows
a.copy(), np.array(a)
a.ravel() on contiguous data
a.flatten()
a[:, None], np.expand_dims, np.squeeze
a.astype(t)
a.view(dtype)
every arithmetic result a + 1, np.sqrt(a)
print (np.shares_memory(row, m), np.shares_memory(picked, m), row.base is not None )
work[ 0 , 0 ] = 99 # m is unchanged
print (m[ 0 , 0 ], work[ 0 , 0 ], m.T.flags[ "C_CONTIGUOUS" ], m.flags[ "C_CONTIGUOUS" ])
NumPy 2 copy= keyword on np.array, np.asarray, astype and reshape:
copy=
Meaning
True
always copy
None (default of asarray, reshape)
copy only when needed
False
never copy; raise ValueError if a copy is needed (NumPy 1 meant “copy if needed”)
Two shapes are compatible when, compared from the right , each pair of sizes is equal or one of them is 1. A missing axis counts as 1. The result takes the larger size of each pair.
A
B
Result
Use
(3, 4)
()
(3, 4)
a scalar everywhere
(3, 4)
(4,)
(3, 4)
one value per column
(3, 4)
(3, 1)
(3, 4)
one value per row
(3, 1)
(1, 4)
(3, 4)
an outer table
(n, 1, d)
(1, k, d)
(n, k, d)
all pairwise differences
(3, 4)
(3,)
error
right-aligned: 4 vs 3
col_means = m.mean( axis = 0 ) # (4,)
print (m - col_means) # (3, 4) - (4,)
print ((m / m.sum( axis = 1 , keepdims = True )).round( 2 )) # row shares: (3, 4) / (3, 1)
print (np.arange( 3 )[:, None ] * np.arange( 4 )) # (3, 1) * (4,) -> (3, 4)
pts = np.array([[ 0.0 , 0.0 ], [ 3.0 , 4.0 ], [ 6.0 , 8.0 ]])
d = np.sqrt(((pts[:, None , :] - pts[ None , :, :]) ** 2 ).sum( axis =- 1 ))
print (d) # pairwise distances (3, 3)
print (np.broadcast_shapes(( 5 , 1 , 4 ), ( 3 , 1 )))
bad = m - m.sum( axis = 1 ) # (3, 4) - (3,): compare 4 with 3 on the right
ValueError: operands could not be broadcast together with shapes (3,4) (3,)
A ufunc runs element by element in compiled code and broadcasts its inputs.
Kind
Functions
arithmetic
+ - * / // % **, np.add, np.subtract, np.multiply, np.divide, np.power, np.mod
math
np.sqrt, np.exp, np.log, np.log1p, np.expm1, np.log10, np.abs, np.sign
trigonometry
np.sin, np.cos, np.arctan2(y, x), np.deg2rad, np.hypot
rounding
np.round(a, 2), np.floor, np.ceil, np.trunc, np.rint
two-array min/max
np.maximum(a, b), np.minimum(a, b), np.fmax (ignores NaN)
comparison
> >= == !=, np.greater, np.isclose(a, b, rtol, atol)
logic
&, |, ^, ~, np.logical_and, np.logical_not
float tests
np.isnan, np.isinf, np.isfinite
bits
np.left_shift, np.bitwise_and, np.bitwise_count
Ufunc method or argument
Does
Example
f.reduce(a, axis)
fold an axis
np.add.reduce(x) = x.sum()
f.accumulate(a)
running result
np.maximum.accumulate(x): running max
f.outer(a, b)
every pair
np.multiply.outer(a, b)
f.at(a, idx, b)
in place, repeats count
np.add.at(counts, idx, 1)
out=
write into an existing array
np.sqrt(x, out=buf)
where=
compute only where True (others keep out)
np.log(x, out=z, where=x > 0)
x = np.array([ 3 , 1 , 4 , 1 , 5 , 9 , 2 ])
print (np.add.reduce(x), np.add.accumulate(x), np.maximum.accumulate(x))
print (np.multiply.outer([ 1 , 2 ], [ 1 , 10 , 100 ]))
v = np.array([ 4.0 , 0.0 , - 1.0 , 9.0 ])
np.sqrt(v, out = safe, where = v > 0 ) # no warning for 0 or negatives
print (safe, np.diff(x), np.cumprod([ 1 , 2 , 3 , 4 ]))
with np.errstate( divide = "ignore" ): # silence one known warning locally
print (np.log(np.array([ 1.0 , 0.0 ])))
25 [ 3 4 8 9 14 23 25] [3 3 4 4 5 9 9]
[2. 0. 0. 3.] [-2 3 -3 4 4 -7] [ 1 2 6 24]
The named axis disappears. axis=0 collapses the rows and gives one result per column. axis=1 collapses the columns and gives one result per row.
Call
Shape from (2, 3, 4)
a.sum()
scalar
a.sum(axis=0)
(3, 4)
a.sum(axis=-1)
(2, 3)
a.sum(axis=(0, 1))
(4,)
a.sum(axis=1, keepdims=True)
(2, 1, 4)
Function
Note
sum, prod, mean, median, min, max
np.median is a function, not a method
std, var
ddof=0 (population) by default; pandas uses ddof=1
argmin, argmax
the first position; flat index unless axis=
cumsum, cumprod, np.cumulative_sum(include_initial=True)
running totals
np.percentile(a, q), np.quantile(a, q)
q in 0–100 / 0–1; method="linear" default
any, all, np.count_nonzero
for boolean arrays
np.ptp(a)
max − min (the method a.ptp() was removed)
np.average(a, weights=w)
a weighted mean
np.histogram(a, bins)
counts and edges
np.corrcoef(X, rowvar=False), np.cov(...)
columns as variables
print (m.sum(), m.sum( axis = 0 ), m.sum( axis = 1 ), m.mean( axis = 1 ))
print (m.max( axis = 0 ), m.argmax( axis = 1 ), np.unravel_index(m.argmax(), m.shape))
print (m.cumsum( axis = 1 )[ 1 ], np.percentile(m, [ 25 , 50 , 75 ]), np.median(m))
print ( round ( float (m.std()), 3 ), round ( float (m.std( ddof = 1 )), 3 ))
print (np.average([ 1.0 , 2.0 , 3.0 ], weights = [ 3 , 1 , 0 ]), np.ptp(m, axis = 1 ))
counts, edges = np.histogram([ 1 , 2 , 2 , 3 , 8 ], bins = [ 0 , 2 , 4 , 10 ])
66 [12 15 18 21] [ 6 22 38] [1.5 5.5 9.5]
[ 8 9 10 11] [3 3 3] (np.int64(2), np.int64(3))
[ 4 9 15 22] [2.75 5.5 8.25] 5.5
NaN (“not a number”) is a float value. One NaN makes sum, mean and max NaN. An integer array cannot hold NaN.
Plain
NaN-aware
sum, prod, cumsum, cumprod
np.nansum, np.nanprod, np.nancumsum, np.nancumprod (NaN as 0 or 1)
mean, median, std, var
np.nanmean, np.nanmedian, np.nanstd, np.nanvar
min, max, argmin, argmax
np.nanmin, np.nanmax, np.nanargmin, np.nanargmax
percentile, quantile
np.nanpercentile, np.nanquantile
print (temps.mean(), np.nanmean(temps), np.nanmedian(temps), np.nanargmax(temps))
print (np.isnan(temps).sum(), np.nan == np.nan, np.isnan(np.nan))
print (np.where(np.isnan(temps), np.nanmedian(temps), temps)) # fill with the median
print (temps[ ~ np.isnan(temps)], np.nan_to_num(temps, nan = 0.0 ))
print (np.array_equal(temps, temps), np.array_equal(temps, temps, equal_nan = True ))
[20.2 22.3 23.4 24.5 38. ]
[20.2 22.3 24.5 38. ] [20.2 22.3 0. 24.5 38. ]
v = np.array([ 2.1 , 5.0 , 12.3 , np.nan])
t = np.array([ 22.0 , 34.0 , 25.0 , 43.0 ])
status = np.select([(v >= 11.2 ) | (t >= 42 ), (v >= 4.5 ) | (t >= 33 )],
[ "fail" , "warn" ], default = "ok" )
print (status, np.where(t > 30 , "hot" , "ok" ))
print (np.clip(t, 20 , 35 ), np.digitize(t, [ 25 , 35 ]))
print (np.digitize(t, [ 25 , 35 ], right = True )) # edges[i-1] < x <= edges[i]
['ok' 'warn' 'fail' 'fail'] ['ok' 'hot' 'ok' 'hot']
[22. 34. 25. 35.] [0 1 1 2]
Function
Does
np.where(cond, a, b)
element-wise if/else; both a and b are computed
np.where(cond)
positions of True (same as np.nonzero)
np.select(conds, choices, default)
if/elif/else; the first true condition wins
np.piecewise(x, conds, funcs)
a different function per region
np.clip(a, lo, hi)
cap values
np.digitize(x, edges)
bin number: edges[i-1] <= x < edges[i]
x = np.array([ 30 , 10 , 50 , 20 , 50 ])
print (np.sort(x), np.argsort(x, stable = True ), np.sort(x)[:: - 1 ])
print (np.argpartition(x, - 2 )[ - 2 :], np.searchsorted([ 10 , 20 , 30 ], [ 15 , 30 ]))
vals, first, inv, cnt = np.unique(x, return_index = True , return_inverse = True ,
print (vals, first, inv, cnt)
print (np.intersect1d([ 1 , 2 , 3 ], [ 2 , 3 , 4 ]), np.union1d([ 1 , 2 ], [ 2 , 5 ]),
np.setdiff1d([ 1 , 2 , 3 ], [ 2 ]))
print (np.sort(m[:, :: - 1 ], axis = 1 )[ 0 ], np.lexsort(([ 2 , 1 , 1 ], [ 0 , 1 , 0 ])))
[10 20 30 50 50] [1 3 0 2 4] [50 50 30 20 10]
[10 20 30 50] [1 3 0 2] [2 0 3 1 3] [1 1 1 2]
np.lexsort((secondary, primary)) sorts by the last key first.
np.unique returns sorted values. NumPy 2 adds np.unique_values, np.unique_counts, np.unique_inverse and np.unique_all.
grid = flat.reshape( 4 , 6 )
print (grid.shape, flat.reshape( 2 , 3 , - 1 ).shape, grid.T.shape) # -1 is inferred
a, b = np.array([ 1 , 2 , 3 ]), np.array([ 4 , 5 , 6 ])
print (np.concatenate([a, b]), np.stack([a, b]).shape, np.stack([a, b], axis = 1 ).shape)
print (np.vstack([a, b]).shape, np.hstack([a, b]).shape, np.column_stack([a, b]).shape)
print (np.concatenate([m, m], axis = 1 ).shape, np.block([[m, m], [m, m]]).shape)
print ([p.tolist() for p in np.split(np.arange( 6 ), 3 )])
print ([ len (p) for p in np.array_split(flat, 5 )])
print (m[:, None , :].shape, np.expand_dims(a, 0 ).shape, np.squeeze(m[:, : 1 ]).shape)
print (np.moveaxis(np.zeros(( 2 , 3 , 4 )), - 1 , 0 ).shape)
print (m.ravel()[: 5 ], m.ravel( order = "F" )[: 5 ]) # row order vs column order
[1 2 3 4 5 6] (2, 3) (3, 2)
Function
Does
a.reshape(r, -1)
new shape, same elements in row (C) order; -1 is inferred
a.ravel() / a.flatten()
to 1-D: a view if possible / always a copy
a.T, np.transpose(a, axes), np.moveaxis
reorder axes
np.concatenate(seq, axis=0)
join along an existing axis
np.stack(seq, axis=0)
join along a new axis (shapes must match)
np.vstack, np.hstack, np.column_stack
rows; columns; 1-D arrays as columns
np.block([[A, B], [C, D]])
assemble a matrix from blocks
np.split(a, n) / np.array_split(a, n)
equal parts (else error) / nearly equal parts
np.split(a, [2, 5])
split before positions 2 and 5
a[:, None], np.expand_dims, np.squeeze
add or drop length-1 axes
Task
Function
Note
matrix or dot product
A @ B, np.matmul, np.dot
* is element-wise
batch of dot products
np.vecdot(a, b) (NumPy 2)
over the last axis
outer product
np.outer(u, v)
u[:, None] * v
named-axis products and contractions
np.einsum("ij,jk->ik", A, B)
"ii->" is the trace
square system Ax = b
np.linalg.solve(A, b)
LinAlgError if singular
least squares
np.linalg.lstsq(X, y)
returns coef, residuals, rank, sv
inverse, determinant
np.linalg.inv, np.linalg.det
rarely needed; prefer solve
symmetric eigen
np.linalg.eigh(S)
real values, ascending
general eigen
np.linalg.eig(M)
complex128 on NumPy 2.5, even for real results
SVD
np.linalg.svd(M, full_matrices=False)
s descending; signs arbitrary
norm, rank, condition
np.linalg.norm, matrix_rank, cond
large cond: unstable solve
pseudo-inverse
np.linalg.pinv(M)
for non-square or singular matrices
data = np.genfromtxt( "data/houses.csv" , delimiter = "," , skip_header = 1 , usecols = ( 2 , 13 ))
sqft, price = data[:, 0 ], data[:, 1 ]
X = np.column_stack([np.ones_like(sqft), sqft]) # design matrix with intercept
coef, * _ = np.linalg.lstsq(X, price)
print (data.shape, coef.round( 1 ))
A = np.array([[ 3.0 , 1.0 ], [ 1.0 , 2.0 ]])
sol = np.linalg.solve(A, b)
print (sol, np.allclose(A @ sol, b), round ( float (np.linalg.det(A)), 3 ))
w, vecs = np.linalg.eigh(A) # symmetric: use eigh
print (w, np.linalg.eig(A).eigenvalues.dtype)
U, s, Vt = np.linalg.svd(m, full_matrices = False )
print (s, np.linalg.matrix_rank(m), np.allclose(U * s @ Vt, m))
print (np.linalg.norm([ 3.0 , 4.0 ]), np.vecdot(pts, pts))
(3000, 2) [-130345.1 326.8]
[22.409 1.955 0. ] 2 True
Make one generator with a seed and pass it around. Do not use the legacy global functions (np.random.seed, np.random.rand).
rng = np.random.default_rng( 42 )
print (rng.normal( 0 , 1 , size = 3 ), rng.integers( 1 , 7 , size = 5 ))
print (rng.random( 2 ), rng.uniform( 10 , 20 , size = 2 ))
print (rng.choice([ "a" , "b" , "c" ], size = 4 , p = [ 0.5 , 0.3 , 0.2 ]))
print (rng.choice( 10 , 3 , replace = False ))
print (rng.permutation( 5 ), rng.poisson( 4.0 , size = 3 ), rng.binomial( 10 , 0.5 , size = 3 ))
same = np.random.default_rng( 7 ).random( 3 ) == np.random.default_rng( 7 ).random( 3 )
print (same.all(), [ int (c.integers( 100 )) for c in rng.spawn( 2 )])
[ 0.305 -1.04 0.75 ] [1 5 2 1 4]
[0.761 0.786] [11.281 14.504]
[1 0 4 3 2] [7 1 6] [3 5 4]
Legacy (avoid)
Generator method
np.random.seed(42)
rng = np.random.default_rng(42)
np.random.rand(3), np.random.random(3)
rng.random(3)
np.random.randn(3)
rng.standard_normal(3)
np.random.normal(m, s, n)
rng.normal(m, s, n)
np.random.randint(lo, hi, n)
rng.integers(lo, hi, n) (endpoint=True to include hi)
np.random.choice(a, n)
rng.choice(a, n, replace=..., p=...)
np.random.shuffle(a)
rng.shuffle(a) (in place), rng.permutation(a) (copy)
np.random.uniform, poisson, binomial, exponential
the same names on rng
one seed for several processes
rng.spawn(n) or np.random.SeedSequence(42).spawn(n)
names = np.array([ " ana " , "Bo" , "cy" ])
print (np.strings.upper(np.strings.strip(names)), np.strings.str_len(names))
days = np.arange( "2024-05-01" , "2024-05-04" , dtype = "datetime64[D]" )
print (days, (days[ - 1 ] - days[ 0 ]).astype( int ))
print (np.datetime64( "2024-05-01" ) + np.timedelta64( 30 , "D" ))
print (np.busday_count( "2024-05-01" , "2024-05-31" ))
['ANA' 'BO' 'CY'] [6 2 2]
['2024-05-01' '2024-05-02' '2024-05-03'] 2
np.save( "output/a.npy" , a) # binary; keeps shape and dtype
a = np.load( "output/a.npy" )
np.savez_compressed( "output/all.npz" , x = X, y = price)
with np.load( "output/all.npz" ) as f: # a lazy dict-like archive
X, price = f[ "x" ], f[ "y" ]
np.savetxt( "output/a.csv" , X, delimiter = "," , fmt = " %.2f " , header = "one,sqft" )
raw = np.loadtxt( "data/readings.txt" ) # strict: a blank cell raises
gaps = np.genfromtxt( "data/sensors.csv" , delimiter = "," , skip_header = 1 ,
usecols = ( 2 , 3 , 4 )) # blank cells -> nan
np.strings (new in NumPy 2) holds the vectorized string functions: upper, lower, strip, replace, startswith, find, str_len, slice and more. The older np.char module still works. For real text tables, use pandas or Polars.
These names raise AttributeError on NumPy 2. Old tutorials still use them.
Removed
Use instead
np.NaN, np.NAN
np.nan
np.Inf, np.Infinity, np.infty, np.PINF
np.inf
np.NINF
-np.inf
np.float_
np.float64
np.complex_, np.cfloat
np.complex128
np.string_
np.bytes_
np.unicode_
np.str_
np.bool8
np.bool (or np.bool_)
np.object0, np.int0, np.uint0
np.object_, np.intp, np.uintp
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.msort(a)
np.sort(a, axis=0)
np.asfarray(a)
np.asarray(a, dtype=np.float64)
np.find_common_type
np.result_type or np.promote_types
np.cast[t](a)
a.astype(t)
a.ptp(), a.newbyteorder()
np.ptp(a), a.view(a.dtype.newbyteorder())
np.issubclass_, np.set_string_function
issubclass, np.set_printoptions
print (np.nan, np.inf, np.float64, np.prod([ 2 , 3 ]), np.isin([ 1 , 5 ], [ 5 ]))
nan inf <class 'numpy.float64'> 6 [False True]
AttributeError: `np.NaN` was removed in the NumPy 2.0 release. Use `np.nan` instead.
Other NumPy 2 changes that affect old code:
repr() of a scalar shows its type: np.float64(3.0). print() and f-strings still show 3.0. Lists of NumPy scalars print as [np.int64(1), ...]; use .tolist().
The promotion rules above (NEP 50): NumPy scalars are strong, Python numbers are weak, values do not matter.
np.array(x, copy=False) raises when a copy is needed. Use np.asarray(x).
The default integer is int64 on Windows too.
np.linalg.eig returns complex arrays on NumPy 2.5.
Trap
Symptom
Fix
and, or, not on arrays
ValueError: The truth value of an array ... is ambiguous
&, |, ~ with parentheses
a > 1 & b < 2
wrong mask or error: & binds tighter than >
(a > 1) & (b < 2)
editing a slice
the original array changes too
a[1:3].copy() before you edit
x == np.nan
always False
np.isnan(x)
one NaN in the data
mean or sum is nan
np.nanmean, np.nansum
small integer dtypes
np.array([100], np.int8) * 2 is [-56], no warning
upcast with astype(np.int64) first
int8_array + 300
OverflowError on NumPy 2
use a wider dtype
float32 data plus np.float64(...)
silently becomes float64 on NumPy 2
use a Python float or cast the scalar
astype(int) on floats
truncates toward zero, NaN gives garbage
np.round first; handle NaN first
np.round(2.5)
2.0 (round half to even)
expected; use np.floor(x + 0.5) for half up
(n, m) - (n,)
ValueError: operands could not be broadcast
keepdims=True or [:, None]
a[[0, 1], [2, 3]]
2 elements, not a 2 × 2 block
a[np.ix_([0, 1], [2, 3])]
counts[idx] += 1 with repeats
each position counts once
np.add.at or np.bincount
np.std(a) vs pandas .std()
different numbers
NumPy ddof=0, pandas ddof=1; pass ddof
np.empty(n)
random-looking values
np.zeros or fill every cell
np.arange(0, 1, 0.1)
length surprises from float steps
np.linspace(0, 1, 11)
reshape on the wrong order
values land in the wrong rows
check the row order; order="F" for columns
eigenvector and SVD signs
signs flip between versions or machines
do not interpret a sign alone
np.linalg.eig dtype
complex128 even for real results
eigh for symmetric matrices
printing scalars in containers
[np.float64(1.5)]
.tolist(), float(x)
legacy random API
non-reproducible code, shared global state
rng = np.random.default_rng(42)
removed aliases
AttributeError: np.NaN was removed
see the table above
object or <U arrays
slow, no vectorized math
NumPy for numbers; pandas or Polars for text
np.vectorize(f)
no speed-up: it is a Python loop
write the math with ufuncs, np.where or np.select
growing with np.append in a loop
slow: a full copy each time
collect in a list, then one np.array