bhylu.com

Advertisements

NumPy Zeros, Ones and Full

Choose an initial value that has meaning for the calculation. zeros and full initialize their storage, while empty leaves element contents unspecified.

How it works

A zero can mean an actual measured amount, so do not use a zero-filled array to represent missing readings unless a separate validity mask explains it. full is useful for an explicit placeholder such as NaN in a floating array. empty can avoid initialization work when every position will be assigned before reading, but its initial values are not a predictable example. Dtype and shape should be chosen together.

Run the code

Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.

For local work, use a separate virtual environment and run python filled-arrays.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.

Example

filled-arrays.py

import numpy as np

totals = np.zeros(3, dtype=np.int64)
flags = np.ones((2, 2), dtype=bool)
missing = np.full(3, np.nan)
print(totals.tolist())
print(flags.all())
print(np.isnan(missing).tolist())

Expected result

[0, 0, 0]
True
[True, True, True]

Each initialized array has a deliberate starting meaning. The missing values require floating representation, while flags use Boolean values. Later lessons show how to exclude missing readings from an average.

Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.