Reshaping NumPy Arrays
In real-world data processing, data rarely comes in the exact shape we need. NumPy provides powerful tools to reshape arrays without changing the actual data.
Reshaping is essential when preparing data for machine learning models, matrix operations, and numerical computations.
Understanding Array Shape
Every NumPy array has a shape attribute that describes its dimensions.
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 60])
print(arr.shape)
Output:
(6,)
This array has a single dimension with 6 elements.
Reshaping a 1D Array into 2D
The reshape() method allows you to change the shape of an array.
The total number of elements must remain the same.
reshaped = arr.reshape(2, 3)
print(reshaped)
Output:
[[10 20 30]
[40 50 60]]
The data is rearranged into 2 rows and 3 columns.
Automatic Dimension Calculation
NumPy allows you to use -1 to automatically calculate one dimension.
auto_shape = arr.reshape(3, -1)
print(auto_shape)
Output:
[[10 20]
[30 40]
[50 60]]
NumPy automatically figures out the correct number of columns.
Reshaping Multi-Dimensional Arrays
Reshaping also works on multi-dimensional arrays.
matrix = np.array([[1, 2, 3],
[4, 5, 6]])
print(matrix.shape)
Output:
(2, 3)
Now reshape it into a single row.
flat = matrix.reshape(1, 6)
print(flat)
Output:
[[1 2 3 4 5 6]]
Flattening Arrays
Flattening converts a multi-dimensional array into a one-dimensional array.
Using flatten()
flattened = matrix.flatten()
print(flattened)
Output:
[1 2 3 4 5 6]
This creates a new copy of the data.
Using ravel()
The ravel() method returns a flattened view when possible.
raveled = matrix.ravel()
print(raveled)
Output:
[1 2 3 4 5 6]
This is more memory-efficient than flatten().
When Reshaping is Used in Practice
Reshaping is commonly used when:
- Preparing features for machine learning models
- Converting tabular data into matrices
- Working with images and signals
- Performing linear algebra operations
Understanding reshaping ensures data stays consistent while changing its structure.
Practice Exercise
Exercise
Create a NumPy array with values from 1 to 12 and:
- Reshape it into a 3 × 4 matrix
- Flatten it back into 1D
- Reshape it into 2 × 6 using
-1
Expected Outcome
You should be comfortable reshaping arrays without losing data.
What’s Next?
In the next lesson, you will learn how to join and split arrays using stacking and splitting techniques.