Reshaping arrays is a common operation in NumPy that allows you to change the dimensions of an array without modifying its data.
This is particularly useful for preparing data for machine learning models, data processing, or numerical analysis, where you may need to reformat data into specific shapes.
In this tutorial, we will cover:
- Basic Reshaping with reshape()
- Flattening and Raveling Arrays
- Resizing Arrays with resize()
- Using transpose() for Transposing Arrays
- Changing Array Dimensions with expand_dims and squeeze
Let’s dive into each topic with code examples.
1. Basic Reshaping with reshape()
The reshape() function is the primary method for reshaping arrays in NumPy.
It returns a new array with a specified shape, without changing the data.
Example 1: Reshaping a 1D Array to 2D
import numpy as np # Create a 1D array array_1d = np.array([1, 2, 3, 4, 5, 6]) # Reshape to 2D (2 rows, 3 columns) array_2d = array_1d.reshape(2, 3) print("2D Array (2x3):\n", array_2d)
Output:
2D Array (2x3): [[1 2 3] [4 5 6]]
Example 2: Reshaping a 1D Array to 3D
# Reshape to 3D (2 layers, 3 rows, 1 column) array_3d = array_1d.reshape(2, 3, 1) print("\n3D Array (2x3x1):\n", array_3d)
Output:
3D Array (2x3x1): [[[1] [2] [3]] [[4] [5] [6]]]
- Explanation: Reshaping to 3D requires a total number of elements that matches the original array’s size.
Example 3: Using -1 in reshape() for Automatic Dimension Calculation
You can use -1 as a placeholder to let NumPy calculate the dimension automatically.
# Automatically calculate the number of rows array_auto = array_1d.reshape(-1, 2) print("\nReshaped Array with -1:\n", array_auto)
Output:
Reshaped Array with -1: [[1 2] [3 4] [5 6]]
- Explanation: Here, -1 tells NumPy to infer the appropriate dimension based on the remaining elements, resulting in a shape of (3, 2).
2. Flattening and Raveling Arrays
Flattening an array reduces it to a single dimension, regardless of its original shape.
NumPy offers two main functions for this: flatten() and ravel().
Example 4: Flattening an Array with flatten()
# Create a 2D array array_2d = np.array([[1, 2, 3], [4, 5, 6]]) # Flatten the array to 1D flattened_array = array_2d.flatten() print("Flattened Array:\n", flattened_array)
Output:
Flattened Array: [1 2 3 4 5 6]
- Explanation: flatten() creates a new 1D array, leaving the original array unchanged.
Example 5: Flattening an Array with ravel()
# Ravel the array to 1D raveled_array = array_2d.ravel() print("\nRaveled Array:\n", raveled_array)
- Explanation: ravel() also returns a 1D view of the array but does not make a copy if possible, making it more memory-efficient.
3. Resizing Arrays with resize()
Unlike reshape(), which returns a new array, resize() modifies the array in-place.
If the new size is larger than the original, resize() fills extra elements with zero.
Example 6: Resizing an Array In-Place
# Create a 1D array array_resize = np.array([1, 2, 3, 4]) # Resize to a 2x3 array array_resize.resize(2, 3) print("Resized Array:\n", array_resize)
Output:
Resized Array: [[1 2 3] [4 0 0]]
- Explanation: resize() adjusts the shape in-place and fills missing elements with zero.
Example 7: Resizing to a Smaller Array
# Resize the array to a smaller size array_resize.resize(2, 2) print("\nResized to Smaller Array:\n", array_resize)
Output:
Resized to Smaller Array: [[1 2] [3 4]]
- Explanation: resize() truncates elements when resizing to a smaller shape.
4. Using transpose() for Transposing Arrays
The transpose() function swaps the array dimensions, useful for changing the orientation of data.
Example 8: Transposing a 2D Array
# Create a 2D array array_2d = np.array([[1, 2, 3], [4, 5, 6]]) # Transpose the array transposed_array = array_2d.transpose() print("Transposed Array:\n", transposed_array)
Output:
Transposed Array: [[1 4] [2 5] [3 6]]
- Explanation: transpose() swaps rows and columns.
Example 9: Transposing a 3D Array
For 3D arrays, you can specify the order of axes.
# Create a 3D array array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) # Transpose the 3D array (swap first and second axis) transposed_3d = array_3d.transpose(1, 0, 2) print("\nTransposed 3D Array:\n", transposed_3d)
Output:
Transposed 3D Array: [[[1 2] [5 6]] [[3 4] [7 8]]]
- Explanation: In 3D arrays, transpose() allows reordering axes for more complex transformations.
5. Changing Array Dimensions with expand_dims and squeeze
The expand_dims() function adds an extra dimension to an array, while squeeze() removes dimensions of size one.
Example 10: Expanding Array Dimensions with expand_dims()
# Create a 1D array array_1d = np.array([1, 2, 3]) # Expand dimensions to make it 2D expanded_array = np.expand_dims(array_1d, axis=0) print("Expanded Array (2D):\n", expanded_array) print("Shape:", expanded_array.shape)
Output:
Expanded Array (2D): [[1 2 3]] Shape: (1, 3)
- Explanation: expand_dims() adds an extra dimension, changing the shape from (3,) to (1, 3).
Example 11: Removing Dimensions with squeeze()
# Create a 3D array with a singleton dimension array_3d_singleton = np.array([[[1, 2, 3]]]) # Squeeze to remove dimensions of size 1 squeezed_array = np.squeeze(array_3d_singleton) print("\nSqueezed Array:\n", squeezed_array) print("Shape:", squeezed_array.shape)
Output:
Squeezed Array: [1 2 3] Shape: (3,)
- Explanation: squeeze() removes dimensions with a size of 1, reducing the shape to the minimum necessary.
Summary of Array Reshaping Techniques in NumPy
Function | Description |
---|---|
reshape() | Returns a new array with a specified shape without modifying the original. |
flatten() | Creates a 1D copy of the array, reducing it to a single dimension. |
ravel() | Returns a 1D view if possible (more memory-efficient than flatten()). |
resize() | Modifies the array in-place and fills missing values with zero if the new shape is larger. |
transpose() | Transposes the array, swapping dimensions for 2D, 3D, or higher-dimensional arrays. |
expand_dims() | Adds a new dimension to the array at a specified axis. |
squeeze() | Removes singleton dimensions (dimensions with size 1) from the shape. |
Conclusion
In this tutorial, we explored several ways to reshape arrays in NumPy, including:
- Using reshape() to convert arrays into different shapes.
- Flattening arrays with flatten() and ravel().
- Resizing arrays in-place with resize().
- Transposing arrays with transpose().
- Changing array dimensions with expand_dims() and squeeze().