
The numpy.reshape function is a fundamental tool when working with arrays in Python. At its core, it allows you to change the shape of an existing array without altering its data. This means you can transform a one-dimensional array into a two-dimensional matrix, flatten a matrix into a vector, or reshape arrays into higher dimensions as long as the total number of elements remains constant.
The signature looks like this:
numpy.reshape(a, newshape, order='C')
Here, a is the input array, and newshape is a tuple or int specifying the desired dimensions. The order parameter controls whether the array should be read and written in row-major ('C') or column-major ('F') order.
One subtlety to watch for is that the total number of elements before and after reshaping must match. For example, a (6,) array can be reshaped into (2, 3) or (3, 2), but not into (4, 2) because 4×2=8, which differs from 6.
When you provide -1 in newshape, NumPy infers the dimension automatically. That is incredibly handy when you only know one dimension and want the other calculated for you:
import numpy as np arr = np.arange(12) reshaped = arr.reshape((3, -1)) print(reshaped.shape) # Output: (3, 4)
Here, -1 tells NumPy: “Figure out the size of this dimension so that the total size remains 12.” This makes code flexible and less error-prone when dealing with dynamic data shapes.
Another point to consider is the order argument. The default 'C' order means the array is read/written row-wise (C-style). If you’re working with libraries or formats that use column-major order (like Fortran or MATLAB), setting order='F' ensures reshaping respects that memory layout:
arr = np.array([[1, 2, 3], [4, 5, 6]]) reshaped_c = arr.reshape((3, 2), order='C') reshaped_f = arr.reshape((3, 2), order='F') print(reshaped_c) # [[1 2] # [3 4] # [5 6]] print(reshaped_f) # [[1 4] # [2 5] # [3 6]]
Understanding this subtlety becomes crucial when performance or memory layout matters. The reshaped array is essentially a view of the original data when possible, so no data copy occurs unless necessary.
When reshape cannot return a view (for example, if the order specified is incompatible with the original memory layout), it will create a copy. You can check whether the reshaped array shares memory with the original using np.shares_memory:
reshaped = arr.reshape((6,)) print(np.shares_memory(arr, reshaped)) # True or False depending on reshape
This insight helps avoid unnecessary data duplication, which is important for large datasets.
One last note: if you want to flatten an array, reshape(-1) is often more readable than flatten() or ravel(), since it signals the intent to reshape rather than create a copy:
flat = arr.reshape(-1)
This method returns a view whenever possible, whereas flatten() always returns a copy. This distinction has performance implications when dealing with large arrays.
Getting comfortable with reshape means you can manipulate data layouts fluidly, which is important when preparing inputs for machine learning algorithms, or when interfacing between libraries with different array shape expectations. Now, let’s move on to some of the common scenarios where reshape is not just convenient but necessary.
Amazon Fire TV Stick 4K Select (newest model), start streaming in 4K, AI-powered search, and free & live TV, find shows faster with Alexa+
$39.99 (as of July 15, 2026 15:40 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Common use cases for array reshaping
One of the most common use cases for reshape is preparing data for machine learning models. Many models expect inputs as two-dimensional arrays where rows represent samples and columns represent features. If you start with a flat array or a differently shaped dataset, reshaping can align your data correctly.
import numpy as np # Suppose you have 100 grayscale images of size 28x28 pixels stored in a flat array data = np.random.rand(100, 28*28) # Reshape each image into its 2D form for visualization or processing images = data.reshape((100, 28, 28)) print(images.shape) # (100, 28, 28)
In this example, each image is restored from a flat vector into a 2D matrix representing pixel intensities. That is essential when passing data to convolutional neural networks that expect multi-dimensional input.
Another frequent scenario is when you need to flatten multi-dimensional arrays for algorithms that only accept 1D input. Instead of using flatten(), reshaping with -1 is efficient:
arr = np.array([[1, 2], [3, 4], [5, 6]]) flat = arr.reshape(-1) print(flat) # [1 2 3 4 5 6]
This technique generalizes well to arrays of any dimension, providing a uniform way to collapse data into a vector.
Reshaping is also useful for batching operations. For example, if you have a long time series and want to split it into fixed-size windows for analysis, you can reshape the array accordingly:
time_series = np.arange(1000) window_size = 50 # Ensure the length divides evenly by window_size batched = time_series[:(len(time_series) // window_size) * window_size].reshape(-1, window_size) print(batched.shape) # (20, 50)
Each row now represents a window of 50 time steps, making it easier to apply vectorized operations or feed into models expecting batch input.
Sometimes, reshaping helps when dealing with broadcasting rules. Consider a scenario where you want to multiply a 1D array by each column of a 2D array. Reshaping the 1D array to a column vector aligns dimensions for broadcasting:
matrix = np.array([[1, 2, 3], [4, 5, 6]]) vector = np.array([10, 20]) # Reshape vector to (2,1) to broadcast across columns result = vector.reshape(-1, 1) * matrix print(result) # [[10 20 30] # [80 100 120]]
This approach avoids explicit loops and leverages NumPy’s optimized broadcasting for performance.
In data preprocessing, reshaping often pairs with transpose() or swapaxes() to reorder dimensions after reshaping. For instance, if you have a 3D array representing (samples, height, width) but need (samples, width, height) for a particular library, you can chain reshape with transpose:
data = np.random.rand(10, 28, 28) # Flatten images and then reshape back with swapped axes flat = data.reshape(10, -1) swapped = flat.reshape(10, 28, 28).transpose(0, 2, 1) print(swapped.shape) # (10, 28, 28)
Here, while the shape remains the same, the pixel layout is effectively rotated, which can be critical for correct feature extraction.
Finally, reshaping helps when interfacing with external data formats. For example, CSV files or databases often store tabular data that, when loaded, needs reshaping into multi-dimensional arrays for numerical computations:
import pandas as pd
df = pd.DataFrame({
'feature1': range(6),
'feature2': range(10, 16),
'feature3': range(20, 26)
})
arr = df.to_numpy()
reshaped = arr.reshape((2, 3, 3))
print(reshaped.shape) # (2, 3, 3)
Such transformations facilitate batch processing or feeding data into APIs expecting specific input shapes.

