bhylu.com

Advertisements

NumPy Shape and Axes

Shape describes the length of each dimension. An axis identifies which dimension an operation follows; its meaning comes from your data model.

How it works

In this fixture rows are collection sites and columns are successive days. The array has two dimensions and six values. NumPy does not know those labels, so write them down before reducing or reshaping the data. A scalar array has no axes, a one-dimensional array has one axis and a table-shaped array has two. Higher dimensions are useful when the problem genuinely has another coordinate, such as trial, site and day.

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 dimensions.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

dimensions.py

import numpy as np

# Rows: roof A and roof B. Columns: three days.
litres = np.array([[12, 18, 24], [6, 9, 15]], dtype=np.int64)
print(litres.ndim, litres.shape, litres.size)
print(litres.sum(axis=0).tolist())
print(litres.sum(axis=1).tolist())

Expected result

2 (2, 3) 6
[18, 27, 39]
[54, 30]

Axis zero combines sites and leaves one result per day. Axis one combines days and leaves one total per site. The different output shapes help verify that the calculation answers the intended question.

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