We use reshape() to change the shape of data without changing its values. It helps us organize data in a way that fits our analysis or model.
0
0
reshape() for changing dimensions in NumPy
Introduction
You have a flat list of numbers but want to see them as a table with rows and columns.
You want to prepare image data from a 1D array to a 2D or 3D array for processing.
You need to change the shape of data to match the input requirements of a machine learning model.
You want to split a dataset into smaller chunks or combine smaller arrays into a bigger one.
Syntax
NumPy
numpy_array.reshape(new_shape)
new_shape is a tuple that defines the new dimensions, like (rows, columns).
One dimension can be -1, which means numpy will calculate it automatically.
Examples
This changes a 1D array of 6 elements into a 2x3 matrix.
NumPy
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) new_arr = arr.reshape((2, 3)) print(new_arr)
Using -1 lets numpy figure out the second dimension automatically.
NumPy
import numpy as np arr = np.arange(8) new_arr = arr.reshape((2, -1)) print(new_arr)
This flattens a 2D array into a 1D array.
NumPy
import numpy as np arr = np.array([[1, 2], [3, 4], [5, 6]]) new_arr = arr.reshape((6,)) print(new_arr)
Sample Program
This program shows how to reshape a 1D array into different 2D shapes. It also demonstrates using -1 to let numpy calculate one dimension automatically.
NumPy
import numpy as np # Create a 1D array with 12 elements arr = np.arange(12) print('Original array:') print(arr) # Reshape to 3 rows and 4 columns reshaped_arr = arr.reshape((3, 4)) print('\nReshaped to 3x4:') print(reshaped_arr) # Reshape to 2 rows and let numpy decide columns reshaped_auto = arr.reshape((2, -1)) print('\nReshaped to 2 rows and automatic columns:') print(reshaped_auto)
OutputSuccess
Important Notes
The total number of elements must stay the same when reshaping.
If you use a shape that doesn't match the total elements, numpy will give an error.
Reshape does not change the data, only how it is viewed.
Summary
reshape() changes the shape of an array without changing its data.
You can specify new dimensions as a tuple, using -1 for automatic calculation.
Always keep the total number of elements the same when reshaping.