smartyfy.mrindigi.com

Python Master Course V2 — 121. NumPy Arrays, Shapes and Vectorized Computation

What you will be able to do

  • Create arrays with intentional shape and dtype
  • Use indexing, broadcasting and reductions correctly
  • Explain views, copies and numerical tolerances

Prerequisites: 031–040: collections; 051–060: functions; 065–067: package environments.

Your local workspace

Use CPython 3.11 or newer; Python 3.12 or 3.13 is a practical baseline. This lesson uses only your CPU and artificial data. Create a new folder named lesson121, open a terminal there, and keep all named files inside it. Do not use real customer records. Commands marked shell belong in the terminal; Python belongs in the named .py files. Run commands from this folder unless a step explicitly changes directories.

Create an isolated environment with python -m venv .venv. On macOS/Linux activate it with source .venv/bin/activate; in Windows PowerShell use .venv\Scripts\Activate.ps1. If activation is restricted, invoke .venv\Scripts\python.exe directly rather than changing security settings. Use the interpreter that your installation calls python or python3 consistently. Installation needs internet access once; all lesson exercises run locally.

python -m pip install numpy pytest

The examples target the documented APIs linked below. Record your installed versions with python -m pip freeze when preserving a result. Expected outputs describe what the supplied deterministic examples should produce; they are not a claim that your environment has already passed a test.

An array has values, a shape and a numerical type

NumPy introduces ndarray, a multidimensional container designed for numerical computation. A Python list can hold unrelated kinds of objects; a typical numerical array stores elements with one dtype. dtype affects precision, range, missing-value representation and memory. An integer array cannot naturally represent NaN, so this lesson deliberately uses floating-point arrays for measurements that may be missing. Converting to float does not make measured values exact real numbers.

Shape is a tuple describing the length of each axis. Our sensor matrix has three observations and two sensors, so its shape is (3, 2). Axis 0 runs down observations; axis 1 runs across sensors. Reducing axis 0 produces one value per sensor. Reducing axis 1 produces one value per observation. State the meaning of each axis before calculating: correct arithmetic on the wrong axis is still a wrong analysis.

Vectorization expresses operations over arrays rather than writing one Python operation per element. Multiplication by 2 is elementwise; matrix multiplication uses @ and is introduced next. Broadcasting aligns shapes from the trailing dimensions, allowing equal dimensions or dimensions of length one. Subtracting a (2,) sensor-offset vector from a (3, 2) matrix subtracts the appropriate offset from every observation. A (3,) row-offset vector is not compatible in that direction; reshape it to (3, 1).

Slicing often returns a view sharing memory with the original array. Changing that view can change the source. Use copy when independent storage is required, and test ownership assumptions explicitly. Boolean and advanced indexing have different copying behavior; do not infer memory semantics solely from similar-looking syntax. The important question is whether an operation is permitted to mutate its caller's data.

Read shapes before interpreting numbers

import numpy as np

readings = np.array([[10, 20], [20, 30], [30, 40]], dtype=float)
print(readings.shape)
print(readings.mean(axis=0).tolist())
print(readings.mean(axis=1).tolist())
offsets = np.array([10.0, 20.0])
print((readings - offsets).tolist())
view = readings[:, 0]
view[0] = 99
print(readings[0, 0])
independent = readings.copy()
independent[0, 0] = 0
print(readings[0, 0])

Expected output

(3, 2)
[20.0, 30.0]
[15.0, 25.0, 35.0]
[[0.0, 0.0], [10.0, 10.0], [20.0, 20.0]]
99.0
99.0

The view example intentionally mutates the matrix. Run the next lab with its separately constructed data rather than reusing the modified array. This distinction is a practical reason to keep examples self-contained.

Guided lab: summarize a sensor matrix with missing readings

The function below accepts a nonempty two-dimensional numeric matrix. NaN means missing; infinity is rejected, and a completely missing sensor column is rejected because its mean is undefined. It returns valid counts, sensor means and centered readings. Missing measurements remain missing after centering. The function must not modify the caller's array. Save sensors.py.

import numpy as np


def summarize_sensors(values):
    data = np.asarray(values, dtype=float)
    if data.ndim != 2 or 0 in data.shape:
        raise ValueError("expected a nonempty observation-by-sensor matrix")
    if np.isinf(data).any():
        raise ValueError("infinite readings are not supported")
    counts = np.sum(~np.isnan(data), axis=0)
    if np.any(counts == 0):
        raise ValueError("every sensor needs an observed reading")
    means = np.nanmean(data, axis=0)
    centered = data - means
    return counts, means, centered
import numpy as np
from sensors import summarize_sensors

values = np.array([[10, 20], [20, np.nan], [30, 40]], dtype=float)
counts, means, centered = summarize_sensors(values)
print(counts.tolist())
print(means.tolist())
print(centered[0].tolist())
print(bool(np.isnan(centered[1, 1])))

Expected output

[3, 2]
[20.0, 30.0]
[-10.0, -10.0]
True

Save the checks as test_sensors.py. Floating-point results are compared with a stated absolute tolerance near zero and a relative tolerance for magnitude. Shape assertions remain exact; a tolerant numerical comparison must not conceal an unintended broadcast or changed dimensionality.

import numpy as np
import pytest
from sensors import summarize_sensors


def test_values_and_no_mutation():
    data = np.array([[10, 20], [20, np.nan], [30, 40]], dtype=float)
    before = data.copy()
    counts, means, centered = summarize_sensors(data)
    assert centered.shape == (3, 2)
    np.testing.assert_array_equal(counts, [3, 2])
    np.testing.assert_allclose(means, [20, 30], rtol=1e-12, atol=1e-12)
    np.testing.assert_allclose(np.nanmean(centered, axis=0), [0, 0],
                               rtol=1e-12, atol=1e-12)
    np.testing.assert_allclose(data, before, equal_nan=True)


@pytest.mark.parametrize("bad", [[], [1, 2], [[np.nan]], [[np.inf]]])
def test_invalid_shapes_and_values(bad):
    with pytest.raises(ValueError):
        summarize_sensors(bad)
python -m pytest -q test_sensors.py

Expected result: five cases pass. Add a one-row, two-sensor matrix and explain why it is valid. Then try a one-dimensional list and explain why its axis meaning is ambiguous. Rejecting that ambiguity is safer than silently guessing whether the numbers represent sensors or observations.

Numerical debugging starts with shape and meaning

Inspect shape and dtype before printing thousands of values. A broadcast can produce a huge intermediate array, so vectorized does not automatically mean memory-efficient. Compare intended and actual shapes at each boundary. If subtraction unexpectedly creates a square matrix, inspect whether one operand is (n, 1) and another is (n,).

NaN is not equal to itself, so use np.isnan rather than value == np.nan. np.nanmean ignores missing observations, which changes the denominator per column. Reporting valid counts alongside means prevents a one-reading average from looking as well supported as a hundred-reading average. Missingness may be informative; these summaries do not establish that ignoring it is statistically unbiased.

Questions worth asking

Why does axis=0 give one value per sensor?

It collapses the observation axis and keeps the sensor axis. For shape (3, 2), the result has shape (2,). Drawing a three-row, two-column grid before reducing is often more reliable than memorizing “rows” and “columns” as slogans.

Why is data – means valid broadcasting?

data has shape (3, 2) and means has shape (2,). Their trailing dimensions match, so the same two sensor means are used for every observation. The operation expresses per-column centering, not a separate mean for each row.

Can np.asarray guarantee an independent copy?

No. If the input already has an appropriate array representation, it may reuse existing storage. Our function avoids in-place mutation and creates centered through subtraction. Use an explicit copy when independent ownership is part of the contract.

Why not compare every float with ==?

Binary floating-point arithmetic can accumulate small representation and rounding differences. Use a tolerance justified by scale and domain, while checking shape and exact discrete counts separately. An enormous tolerance can conceal a real numerical defect.

Is replacing NaN with zero harmless?

No. Zero is an observed numerical value and affects means, totals and relationships. Missing means unknown or absent. Choose a missing-data policy based on the analysis goal and report its assumptions rather than silently inventing measurements.

Does vectorization always make code faster?

No. It can remove Python-loop overhead, but may allocate large intermediate arrays or invoke unnecessary work. Measure representative workloads after correctness is established. A tiny clear loop can be preferable to a complex memory-heavy expression.

Practice, then compare your solution

1. Row offsets

How should offsets [1, 2, 3] be shaped to subtract one per observation?

Worked solution and reasoning

Convert them to an array and reshape to (3, 1), then subtract from the (3, 2) matrix. The length-one sensor axis broadcasts each row offset across both sensors.

2. Missing column

What should happen for [[1, NaN], [2, NaN]]?

Worked solution and reasoning

The function raises ValueError because the second sensor has zero observed readings. Reporting a numerical mean there would invent information. A different contract could return a missing mean plus a quality flag, but should state that explicitly.

Mastery checkpoint

Explain every axis, dtype and broadcast in the sensor summary. Demonstrate a shared-memory view and an independent copy. Your deliverable must report valid counts, preserve missingness, reject undefined columns and include tolerance-aware checks without mutating the input.

Official documentation and next steps

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.