NumPy Array Reshaping
Change shape of a numPy array
Reshaping an array means changing its shape (i.e., number of rows and columns) without changing the data.
NumPy provides several methods to reshape arrays efficiently, which is useful in data manipulation, machine learning, and deep learning applications.
.reshape()
Reshaping with The .reshape()
method allows us to change the dimensions of an array while keeping all elements intact.
numpy_array.reshape(rows, columns)
- Rules for Reshaping
- The total number of elements must remain the same.
- The new shape must be compatible with the original number of elements.
# Convert a 1D Array to a 2D Array
import numpy as np
# Original 1D array
arr = np.array([1, 2, 3, 4, 5, 6])
# Reshaping into a 2D array (2 rows, 3 columns)
reshaped_arr = arr.reshape(2, 3)
print(reshaped_arr)
Output:
[[1 2 3]
[4 5 6]]
Note: that the number of elements remains 6 (2 × 3 = 6).
Reshaping to 3D Arrays
You can also reshape into 3D arrays (tensors).
# Convert a 1D Array to a 3D Array
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
# Reshaping into a 3D array (2 matrices, 2 rows, 3 columns)
reshaped_arr = arr.reshape(2, 2, 3)
print(reshaped_arr)
Output:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
Shape Explanation
- The array now has 2 matrices
- Each matrix has 2 rows and 3 columns
-1
(Auto Dimension Calculation)
Using Sometimes, you don’t need to specify all dimensions. NumPy can automatically calculate the missing dimension using -1
.
# Automatically Determine the Number of Rows
arr = np.array([1, 2, 3, 4, 5, 6])
# Let NumPy determine the number of rows
reshaped_arr = arr.reshape(-1, 2) # NumPy calculates rows
print(reshaped_arr)
Output:
[[1 2]
[3 4]
[5 6]]
Why use -1
?
- We specified 2 columns, and NumPy automatically adjusted the number of rows (3 rows).
Flattening (Converting to 1D)
Flattening means converting a multi-dimensional array into a 1D array.
# Flattening a 2D Array
arr = np.array([[1, 2, 3], [4, 5, 6]])
flattened_arr = arr.reshape(-1) # Converts to 1D
print(flattened_arr)
Output:
[1 2 3 4 5 6]
Use Case: Flattening is useful when passing data into machine learning models that require 1D inputs.
ravel()
and flatten()
Reshaping with .flatten()
→ Returns a new copy (modifications don’t affect original)..ravel()
→ Returns a view (modifications affect original).
Difference Between .ravel()
and .flatten()
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Flatten (Creates a copy)
flattened_copy = arr.flatten()
# Ravel (Creates a view)
flattened_view = arr.ravel()
print(flattened_copy) # [1 2 3 4 5 6]
print(flattened_view) # [1 2 3 4 5 6]