Check dimensionality
Inspecting data before numerical operations
NumPy · Pipe
ndarray.shape gives an array's dimensions as a tuple. Direct assignment can request an in-place reshape, but ndarray.reshape is the preferred approach.
ndarray.shape exposes an array's dimensions as a tuple. Although assigning a tuple to this property can attempt an in-place reshape, NumPy recommends ndarray.reshape instead; in-place assignment fails when reshaping requires a copy.
ndarray.shapeA tuple of array dimensions.
arr.shape to inspect the current dimensions without changing the array.-1 dimension can be used when assigning or requesting a shape; NumPy infers that dimension.arr.shape for reshaping in new code; use ndarray.reshape because direct shape assignment is deprecated.import numpy as np
x = np.array([1, 2, 3, 4])
print(x.shape) # (4,)
x = x.reshape(2, 2)
print(x.shape) # (2, 2)Read an array's dimensions with shape; use reshape for the preferred way to create a different shape.
Inspecting data before numerical operations
Validating inputs to a computation
Changing an array's view or layout when appropriate
ndarray.shape return?It returns the array's dimensions as a tuple. For example, a one-dimensional array with four elements has shape (4,), while an array with dimensions 2, 3, and 4 has shape (2, 3, 4).
Follow-up: How should an array be reshaped in modern NumPy? Use ndarray.reshape, which is the preferred approach rather than assigning to arr.shape.
arr.shape?Assigning a tuple to arr.shape attempts to reshape the array in place. The operation fails if a copy would be required, so it is not a general replacement for reshape.
Follow-up: What does a -1 dimension do? Its value is inferred from the array size and the other dimensions.
A shape tuple contains one dimension size per axis, so (2, 3, 4) describes a three-dimensional array. The product of the dimensions must match the number of elements when changing shape.
Follow-up: Why can in-place reshaping fail even when the element count matches? The existing memory layout may require a copy.
numpy.reshapendarray.reshape