NumPy (Numerical Python) is the foundational package for scientific computing and data science in Python. Its central object is the homogeneous, multi-dimensional ndarray, backed by a contiguous block of memory with stride descriptors and dtype metadata, enabling highly performant vectorized execution.
🔗 Related Cheat Sheets: Pandas Cheat Sheet · Scikit-Learn Cheat Sheet · Data Analysis Methods · Python Cheat Sheet
1. Array Dimensions, Axes & Memory Layout
Understanding NumPy requires mastering how axes collapse during aggregation:
1D Array (ndim=1, shape=(3,))
[ 1, 2, 3 ] ──> axis 0
2D Matrix (ndim=2, shape=(2, 3))
axis 1 (Columns ──>)
col 0 col 1 col 2
axis 0 ┌───────┬───────┬───────┐
(Rows) │ 1.5 │ 2.0 │ 3.0 │ row 0
│ ├───────┼───────┼───────┤
▼ │ 4.0 │ 5.0 │ 6.0 │ row 1
└───────┴───────┴───────┘
* Rule: Aggregating along axis=0 (e.g. a.mean(axis=0)) collapses across rows, returning column statistics (shape=(3,));
Aggregating along axis=1 collapses across columns, returning row statistics (shape=(2,)).
3D Tensor (ndim=3, shape=(2, 2, 3))
axis 0: Batch / Depth
axis 1: Rows
axis 2: Columns
2. Imports & Disk I/O
import numpy as np
# 1. Binary I/O (preferred: fastest, preserves shapes and dtypes)
np.save('arr.npy', arr) # Save single array as .npy
arr = np.load('arr.npy') # Load .npy
np.savez('data.npz', a=arr1, b=arr2) # Bundle multiple arrays
np.savez_compressed('data_c.npz', a=arr1) # Compressed archive
data = np.load('data.npz') # Lazy-loaded dictionary: data['a']
# 2. Text File I/O
arr = np.loadtxt('file.txt', delimiter=',')
arr = np.genfromtxt('file.csv', delimiter=',', filling_values=0.0)
np.savetxt('out.csv', arr, delimiter=',', fmt='%.4f')
3. Array Creation & Placeholders
| Creation Strategy | Syntax Example | Notes & Semantics |
|---|---|---|
| From Sequences | np.array([1, 2, 3]) |
1D array from Python list |
| 2D Matrix | np.array([(1, 2, 3), (4, 5, 6)], dtype=float) |
2x3 float matrix |
| Zeros | np.zeros((3, 4)) |
3x4 zero-initialized float array |
| Ones | np.ones((2, 3, 4), dtype=np.int32) |
3D array of ones |
| Constant Fill | np.full((2, 2), 7) |
2x2 array filled with value 7 |
| Identity Matrix | np.eye(4) / np.identity(4) |
4x4 identity matrix with 1s on diagonal |
| Uninitialized | np.empty((3, 2)) |
Allocates memory without clearing (fast, garbage values) |
| Step Interval | np.arange(10, 25, 5) |
Range [10, 25) with step 5: [10, 15, 20] |
| Equally Spaced | np.linspace(0, 2, 9) |
9 evenly spaced points on [0, 2] inclusive |
| Log Spaced | np.logspace(0, 3, 4) |
$10^0$ to $10^3$: [1, 10, 100, 1000] |
Modern Random Number Generation (default_rng)
# NumPy 1.17+ Generator interface
rng = np.random.default_rng(seed=42)
r_float = rng.random((2, 3)) # Uniform floats in [0.0, 1.0)
r_int = rng.integers(1, 10, size=(3, 3)) # Discrete integers in [1, 10)
r_norm = rng.standard_normal((3, 3)) # Standard normal N(0, 1)
rng.shuffle(arr) # In-place shuffle along axis 0
4. Array Attributes & Data Types (Dtypes)
4.1 Structural Inspection
arr = np.array([[1.5, 2.0, 3.0], [4.0, 5.0, 6.0]])
arr.shape # (2, 3) Shape tuple
arr.ndim # 2 Number of dimensions
arr.size # 6 Total element count
arr.dtype # dtype('float64')
arr.itemsize # 8 Bytes per element
arr.nbytes # 48 Total array memory footprint (size * itemsize)
arr.astype(int) # Explicitly casts and returns a new copy
4.2 Standard Dtype Table
⚠️ Note: NumPy 2.x and 1.24+ completely removed aliases like
np.bool,np.object,np.complex. Use standard types or underscore suffixes:
| Type | Canonical Aliases | Byte Size | Use Case |
|---|---|---|---|
np.int32 / np.int64 |
'int32', np.int_ |
4 / 8 bytes | Signed integer indices and counts |
np.uint8 |
'uint8' |
1 byte | Image pixel values (0–255) |
np.float32 |
'float32' |
4 bytes | Single-precision floats (neural network weights) |
np.float64 |
'float64', float |
8 bytes | Standard double-precision scientific floats |
np.complex128 |
'complex128', complex |
16 bytes | Complex numbers (real and imaginary parts in float64) |
np.bool_ |
bool, 'bool' |
1 byte | Boolean masks (True / False) |
np.bytes_ |
'S', bytes |
Fixed | Fixed-length ASCII byte sequences |
np.str_ |
'U', str |
Fixed | Fixed-length Unicode strings |
5. Indexing, Slicing & Views vs. Copies
5.1 Basic Slicing (Returns View, Shares Memory)
a = np.array([1, 2, 3, 4, 5])
b = np.array([[1.5, 2, 3], [4, 5, 6]])
c = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
a[2] # 3
b[1, 2] # 6.0 (Preferred syntax over b[1][2])
b[0:2, 1] # array([2., 5.])
b[:1] # array([[1.5, 2., 3.]]) (Keeps 2D shape)
c[1, ...] # Equivalent to c[1, :, :] (Ellipsis notation)
a[::-1] # array([5, 4, 3, 2, 1]) (Reversed array)
5.2 Boolean Mask Indexing (Returns Copy)
filtered = a[a > 2] # array([3, 4, 5])
# Compound conditions require bitwise operators &, |, ~ with parentheses:
combined = a[(a > 1) & (a < 5)] # array([2, 3, 4])
a[a < 3] = 0 # In-place conditional assignment
5.3 Fancy Indexing (Returns Copy)
matrix = np.arange(12).reshape(3, 4)
# 1. Coordinate pair extraction ((0,1) and (2,3))
matrix[[0, 2], [1, 3]] # array([1, 11])
# 2. Rectangular grid extraction
matrix[np.ix_([0, 2], [3, 1])] # Rows 0 & 2, columns 3 & 1
5.4 Views vs. Copies Rulebook
| Indexing Method | Syntax Example | Memory Mechanism | Mutation Result |
|---|---|---|---|
| Basic Slicing | sub = arr[0:2, :] |
View | Mutating sub alters parent arr |
| Fancy Indexing | sub = arr[[0, 1]] |
Copy | Independent memory, safe to mutate |
| Boolean Mask | sub = arr[arr > 0] |
Copy | Independent memory |
| Explicit Clone | sub = arr.copy() |
Deep Copy | Allocates new memory |
| View Check | sub.base is not None |
Attribute check | True indicates shared memory view |
6. Shape Reshaping & Flattening
| Operation | Syntax | Mechanism & Details |
|---|---|---|
reshape |
arr.reshape(3, -1) |
Changes shape (-1 automatically infers dimension); returns view |
ravel |
arr.ravel() |
Flattens to 1D, prefers returning a view (zero memory cost) |
flatten |
arr.flatten() |
Flattens to 1D, always returns an independent copy |
T / transpose |
arr.T / np.transpose(arr) |
Transposes axes |
expand_dims |
np.expand_dims(a, axis=0) |
Inserts singleton dimension (equivalent to a[np.newaxis, :]) |
squeeze |
np.squeeze(arr) |
Drops all dimensions of length 1 |
resize |
np.resize(arr, (2, 6)) |
Functional resize; wraps and repeats data if needed |
7. Concatenation, Stacking & Splitting
7.1 Joining Arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
# 1. Concatenate along existing axis
np.concatenate((A, B), axis=0) # Vertical join (4x2)
np.concatenate((A, B), axis=1) # Horizontal join (2x4)
# 2. Stacking helpers
np.vstack((A, B)) # Vertical stack (equivalent to np.r_[A, B])
np.hstack((A, B)) # Horizontal stack (equivalent to np.c_[A, B])
np.column_stack((a, b)) # Stacks 1D arrays as columns into 2D matrix (3x2)
np.stack((A, B), axis=0) # Stacks along brand-new axis (creates 2x2x2 3D array)
7.2 Splitting Arrays
matrix = np.arange(16).reshape(4, 4)
# Horizontal split (along columns into left and right halves)
left, right = np.hsplit(matrix, 2) # Shape (4, 2) each
# Vertical split (along rows into top and bottom halves)
top, bottom = np.vsplit(matrix, 2) # Shape (2, 4) each
8. Math, Linear Algebra & Broadcasting
8.1 Element-wise Operations
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
add_res = a + b # np.add(a, b)
sub_res = a - b # np.subtract(a, b)
mul_res = a * b # np.multiply(a, b) (element-wise dot product)
div_res = a / b # np.divide(a, b)
pow_res = a ** 2 # np.power(a, 2)
np.exp(a) # Exponential e^x
np.log(a) # Natural logarithm ln(x)
np.sqrt(a) # Square root
np.clip(a, a_min=1, a_max=2) # Clamps values to interval [1, 2]
8.2 Matrix Multiplication & Linear Algebra
A = np.array([[1, 2], [3, 4]])
B = np.array([[2, 0], [1, 2]])
# Standard matrix multiplication (Python 3.5+ operator)
C = A @ B # Recommended syntax
C_matmul = np.matmul(A, B)
# Linear algebra module (np.linalg)
inv_A = np.linalg.inv(A) # Matrix inverse
eig_val, eig_vec = np.linalg.eig(A) # Eigenvalues & eigenvectors
det_A = np.linalg.det(A) # Determinant
8.3 Broadcasting Rules
When operating on arrays of different shapes, NumPy applies broadcasting:
- Right-align dimensions: Compares shape tuples starting from the trailing (rightmost) dimension.
- Compatibility check: In each dimension, lengths must either be equal, or one of them must be 1.
- Virtual expansion: Dimensions of size 1 are virtually stretched without physical memory copies.
# (4, 3) matrix + (3,) vector
A = np.ones((4, 3))
b = np.array([10, 20, 30]) # Right-aligned to (1, 3), broadcasted to (4, 3)
result = A + b # Result shape: (4, 3)
9. Aggregations & Comparisons
⚠️ Note: While
sum(),mean(),min(),max()exist as methods onndarray,np.median(),np.percentile(), andnp.corrcoef()must be called as top-level functions (callinga.median()throws anAttributeError).
| Function / Method | Example | Description |
|---|---|---|
sum |
a.sum(axis=0) |
Sum across rows (returns column sums) |
mean |
a.mean(axis=1) |
Mean across columns (returns row means) |
std / var |
a.std(ddof=0) |
Population standard deviation (ddof=1 for sample) |
argmin / argmax |
a.argmax(axis=0) |
Index positions of minimum / maximum values |
cumsum |
a.cumsum(axis=1) |
Cumulative sum prefix matrix |
np.median |
np.median(a, axis=0) |
Median (function call only) |
np.percentile |
np.percentile(a, 75) |
75th percentile (function call only) |
np.corrcoef |
np.corrcoef(matrix) |
Pearson correlation matrix (function call only) |
Comparisons & Where
a = np.array([1, 2, 3])
b = np.array([1, 2, 4])
np.array_equal(a, b) # False (exact equality)
np.allclose(a, b, atol=1e-5) # Floating-point tolerance comparison
np.all(a > 0) # True (all elements satisfy condition)
np.any(a > 2) # True (at least one element satisfies)
cond_res = np.where(a > 1, 100, -1) # array([-1, 100, 100])
10. Sorting & Indirect Indexing
arr = np.array([3, 1, 2])
# 1. In-place sort
arr.sort() # arr is now [1, 2, 3]
# 2. Indirect argsort (returns index array)
scores = np.array([88, 95, 70, 92])
sorted_indices = np.argsort(scores) # array([2, 0, 3, 1])
top2_indices = np.argsort(scores)[-2:] # Top-2 indices