NUMERICAL COMPUTING
Think in arrays.
NumPy becomes predictable when you read the shape, dtype, memory relationship, and axis before you read the values.
01 · FOUNDATION
Array anatomy
Shape gives the data meaningFour facts describe an ndarray
ndim counts dimensions. shape records the length of each dimension. size counts all elements. dtype determines representation and memory cost.
a = np.array([[1, 2, 3],
[4, 5, 6]], dtype=np.float32)Habit: print a.shape and a.dtype before debugging the calculation.
02 · MEMORY
View or copy
The first source of silent bugsA view shares memory
Basic slicing usually returns another window onto the same data. Fancy indexing and boolean indexing usually create independent data.
Original a
np.shares_memory(a, result)03 · SELECTION
Indexing and masks
Select first, then verify the result shapeSlice a two-dimensional array
Rows and columns use separate selectors. The stop position is excluded. A boolean mask selects values and returns a one-dimensional copy.
x[1:3, 2:5] # sub-matrix, shape (2, 3)
x[x > 10] # matching values, shape (n,)
x[(x > 5) & (x < 12)]Combined conditions: use parentheses with &, |, and ~. Python's and and or do not operate element by element.
04 · REDUCTION
Axis removes a dimension
Predict the output shape before the valuesRemove axis 0. One result remains for each column.
[3, 5, 7]shape (3,)Memory anchor: axis identifies the dimension that disappears. keepdims=True keeps its length as 1 so later broadcasting works.
05 · REAL DATA
Missing values propagate
Choose a NaN-aware operation deliberatelyOne NaN can hide the whole result
Ordinary aggregation propagates missing values. NaN-aware functions skip them, so the effective sample size changes.
x = np.array([1.7, -2.3, 3.5, np.nan])
np.mean(x) # nan
np.nanmean(x) # 0.9666...3 valid values
06 · SHAPE LOGIC
Broadcasting
Align shapes from the right(5,), (1,5), and (5,1) differ07 · NUMERIC SAFETY
Dtype and overflow
Automatic conversion does not prevent every erroruint8 calculation
250 + 10 = 4wraps after 255after astype(float32)
250 + 10 = 260correct numeric resultSafe default: convert images, sensor readings, and large accumulations to float32 or float64 before arithmetic.
08 · COMPUTATION
Element-wise or matrix multiplication
The operator expresses the mathematical meaningShapes must be equal or broadcast-compatible. The output follows the broadcast shape.
(2, 3) * (2, 3) → (2, 3)Vectorization: operate on whole arrays. NumPy runs compiled loops over dense memory instead of executing one Python instruction per element.
09 · SELF-CHECK