NumPy Reshaping
reshape changes how values are arranged across dimensions. The total element count must remain compatible with the requested shape.
How it works
A dimension of -1 asks NumPy to infer one length from the remaining information. Only one inferred dimension is allowed. The operation can return a view or require a copy depending on layout and requested traversal, so inspect ownership when later mutation matters. Reshaping is not a way to fill missing measurements or change their chronological meaning; that meaning must still follow the new coordinate interpretation.
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 reshape.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
import numpy as np
values = np.arange(6)
table = values.reshape(2, -1)
print(table.tolist())
print(table.shape)
try:
values.reshape(4, 2)
except ValueError:
print("Rejected incompatible shape")
Expected result
[[0, 1, 2], [3, 4, 5]] (2, 3) Rejected incompatible shape
Six values fit two rows of three. Eight positions would be needed for the rejected shape, and reshape does not invent the missing values. This catches a structural mismatch before downstream arithmetic.
Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.