Array shape tells NumPy how to interpret the same sequence of values as vectors, tables, batches, or higher-dimensional records. Reshaping changes that shape metadata when data from a flat source needs to match the dimensions expected by later array code.
reshape() does not change the number of values in the array. The product of the requested dimensions must equal the original size, and one dimension can be written as -1 when NumPy should calculate it from the remaining dimensions.
A reshape can share memory with the original array when the layout allows it, so later edits may affect the same underlying values. Check the shape and memory relationship near code that depends on the result, and use a copy when the reshaped data must be edited independently.
Related: Flatten an array
Related: Transpose an array
Related: Check view or copy state
import numpy as np values = np.arange(12) grid = values.reshape(3, 4) records = values.reshape(2, -1, 3) print("values shape:", values.shape) print("grid shape:", grid.shape) print(grid) print("records shape:", records.shape) print("same element count:", values.size == grid.size == records.size) print("shares memory:", np.shares_memory(values, grid)) try: values.reshape(5, 3) except ValueError as error: print("bad shape:", error)
The -1 dimension lets NumPy infer the middle size after the batch and feature dimensions are fixed.
$ python array-reshape.py values shape: (12,) grid shape: (3, 4) [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] records shape: (2, 2, 3) same element count: True shares memory: True bad shape: cannot reshape array of size 12 into shape (5,3)
The valid reshapes keep all 12 values. The invalid (5, 3) shape asks for 15 values and raises ValueError before a mismatched array can continue downstream.
shares memory: True means grid and values refer to the same underlying values for this contiguous layout. Use grid.copy() before editing when the original vector must stay unchanged.
Related: Check view or copy state
$ rm array-reshape.py