Introduction
Reshaping arrays is one of the most common tasks when working with NumPy. Whether you're preparing data for machine learning, manipulating multi-dimensional images, or performing vectorized computations, understanding array shapes is essential.
This guide walks through the most important ways to examine and change array shapes in NumPy—with practical examples and lesser-known tricks.
Getting a NumPy Array’s Shape and Size
Before reshaping an array, you must understand its current structure—its shape (dimensions) and its size (number of elements).
1 2 3 4 | import numpy as np np.random.seed(42) data = np.random.randint(0, 100, (4, 5)) |
This produces:
1 2 3 4 | array([[51, 92, 14, 71, 60], [20, 82, 86, 74, 74], [87, 99, 23, 2, 21], [52, 1, 87, 29, 37]]) |
Checking the Shape With .shape
1 | data.shape |
Output:
1 | (4, 5) |
Checking the Number of Elements With .size
1 | data.size |
Output:
1 | 20
|
The rule:
Reshape operations must preserve the total number of elements.
For example:
4 × 5 = 2 × 10 = 10 × 2 = 20
Reshaping a NumPy Array
Using .reshape()
The primary way to change an array’s shape is:
1 | reshaped_data = data.reshape((2, 10)) |
Result:
1 2 | array([[51, 92, 14, 71, 60, 20, 82, 86, 74, 74], [87, 99, 23, 2, 21, 52, 1, 87, 29, 37]]) |
Note: .reshape() returns a view of the array when possible, not a copy.
Using -1 for Automatic Dimension Inference
Let NumPy choose one dimension:
1 | reshaped_data = data.reshape((-1, 2)) |
Ouput
1 2 3 4 5 6 | array([[51, 92], [14, 71], [60, 20], ... [ 1, 87], [29, 37]]) |
But impossible shapes fail:
1 | data.reshape((-1, 3)) |
Error:
1 | ValueError: cannot reshape array of size 20 into shape (3) |
Flattening an Array
To collapse an array to 1D:
1 | flat = data.flatten() |
Output
1 | array([51, 92, 14, 71, 60, 20, ..., 29, 37]) |
You can restore the shape later:
1 | flat.reshape((4, 5)) |
A better alternative: ravel()
flatten() always returns a copy.
ravel() returns a view when possible:
1 | flat_view = data.ravel() |
This is more memory-efficient and often faster.
Transposing an Array
To swap rows and columns:
1 | data.T |
Or, equivalently:
1 | data.transpose() |
Result:
1 2 3 4 5 | array([[51, 20, 87, 52], [92, 82, 99, 1], [14, 86, 23, 87], [71, 74, 2, 29], [60, 74, 21, 37]]) |
Advanced Shape Manipulation
1. Adding or Removing Dimensions With np.newaxis / None
Add a new dimension (often used in ML):
1 | data_3d = data[:, :, np.newaxis] # shape becomes (4, 5, 1) |
Convert a 2D array to a batch of 1 sample:
1 | batch = data[np.newaxis, :] # shape: (1, 4, 5) |
Convert to a column vector:
1 | col = data.flatten()[:, None] # (20, 1) |
2. Using swapaxes and moveaxis
For multi-dimensional arrays:
1 2 | np.swapaxes(arr, 0, 2) np.moveaxis(arr, 2, 0) |
These are essential when working with image tensors (CHW vs HWC formats).
3. Reshaping for Machine Learning Models
ML libraries often require:
- each row = one sample
- each column = one feature
Convert a 4×5 array into 20 samples of 1 feature:
1 | X = data.reshape(-1, 1) |
Convert into a single sample with 20 features:
1 | X = data.reshape(1, -1) |
Reshape a sequence into sliding windows:
1 2 | seq = np.arange(12) windows = seq.reshape(3, 4) # 3 windows of length 4 |
4. Reshaping Images
Represent a 100×100 RGB image:
1 | image = np.random.rand(100, 100, 3) |
Convert to channel-first format (PyTorch):
1 | image_chw = image.transpose(2, 0, 1) # (3, 100, 100) |
Flatten into a vector for ML:
1 | pixels = image.reshape(-1, 3) # 10,000×3 table |
5. Changing Matrix Memory Order (order='C' or 'F')
Row-major (C-style) vs column-major (Fortran-style):
1 | data.reshape((2, 10), order='F') |
This is critical when interfacing with Fortran or MATLAB.
Summary
Here are the key operations covered:
| Operation | Purpose | Example |
|---|---|---|
shape |
Get array dimensions | data.shape |
size |
Total elements | data.size |
reshape |
Change dimensions | data.reshape((2,10)) |
reshape(-1, …) |
Auto-infer dimension | data.reshape(-1,2) |
flatten |
Return 1D copy | data.flatten() |
ravel |
Return 1D view | data.ravel() |
transpose / .T |
Swap axes | data.T |
newaxis |
Add dimensions | data[:, :, None] |
swapaxes, moveaxis |
Reorder axes | moveaxis(arr, 2, 0) |
References
| Links | Site |
|---|---|
| reshape | numpy.org |
| transpose | numpy.org |
| flatten | numpy.org |
| ravel | numpy.org |
| array-manipulation | numpy.org |
