Array Shape and Reshaping
Python · NumPy Library
Theory
The shape of an array is a tuple giving its size along each axis: (6,) is a 1-D array of six values, (2, 3) is two rows and three columns. reshape rearranges the same values into a new shape without changing their order, so np.arange(1, 7).reshape(2, 3) fills row by row: [[1, 2, 3], [4, 5, 6]]. The total size must stay the same, and one dimension can be -1 to let NumPy work it out: reshape(3, -1) gives (3, 2).
To go back to 1-D, ravel() returns a flat view when it can, while flatten() always returns an independent copy. arr.T (transpose) swaps rows and columns, turning (2, 3) into (3, 2). arr.reshape(-1, 1) or arr[:, np.newaxis] turns a 1-D array into a single column, the shape scikit-learn expects for one feature.
Why we use it
Data rarely arrives in the shape a function needs. Reshaping lets you turn a flat list of readings into a table, a single feature into a column for scikit-learn, or a matrix into rows ready for plotting, without copying or retyping data.
When to use it
Use reshape when the total number of values fits the new shape, -1 when one size is obvious, .T to swap rows and columns, and ravel or flatten to go back to 1-D. Use flatten when you need a safe copy you will modify.
How it works
- Array with shape (6,)
- Does rows x cols equal arr.size? Yes: reshape(rows, cols) fills row by row. No: ValueError: cannot reshape.
- Use -1 to let NumPy compute one dimension
- arr.T swaps rows and columns
- Need 1-D again? Yes: ravel() for a view, flatten() for a copy. No: Keep the 2-D shape.
- Array in the shape the next step needs
Syntax
arr.shape
arr.reshape(rows, cols)
arr.reshape(-1, 1)
arr.ravel() arr.flatten() arr.TExample
a = np.arange(1, 7)
m = a.reshape(2, 3)
print(m.T.shape) # (3, 2)Key points
- reshape keeps the total size: 6 values fit (2, 3) or (3, 2), not (4, 2)
- Values fill row by row (C order) by default
- Use -1 for one dimension and NumPy calculates it
- ravel may return a view; flatten always copies
- A 1-D array has shape (n,), not (n, 1); reshape(-1, 1) makes a column