NumPy arrays are incredibly flexible, allowing you to transform them into different shapes and dimensions to suit your specific computational tasks. In this tutorial, you’ll learn how to reshape NumPy arrays, flatten them into a single dimension, and manipulate array dimensions effectively using NumPy’s powerful methods.
1. Array Reshaping (reshape())
The reshape()
method changes the shape of an existing NumPy array without modifying its data. This is useful when you need a specific array shape for mathematical operations or data processing.
Syntax:
numpy.reshape(array, newshape)
array: Original array.
newshape: Tuple representing the desired shape.
Example:
import numpy as np
# Original array of shape (2, 6)
arr = np.array([[1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12]])
# Reshape into (3, 4)
reshaped_arr = np.reshape(arr, (3, 4))
print("Reshaped Array:\n", reshaped_arr)
Output:
Reshaped Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Special Cases with reshape()
- You can use
-1
to let NumPy automatically infer the correct dimension:
arr.reshape(4, -1) # NumPy calculates the second dimension automatically
2. Flattening Arrays (flatten() and ravel())
Both flatten()
and ravel()
convert multi-dimensional arrays into a single-dimensional array. However, they differ slightly in terms of memory handling:
flatten()
returns a copy of the original array. Changing the flattened array doesn’t affect the original.ravel()
returns a view (when possible). Modifying the result might affect the original array.
Example with flatten()
# Creating NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Flattened array
flat_arr = arr.flatten()
flat_arr[0] = 99
# Printing arrays
print("Flattened Array (copy):", flat_arr)
print("Original Array after flatten():\n", arr)
Output:
Flattened Array (copy): [99 2 3 4 5 6]
Original Array after flatten():
[[1 2 3]
[4 5 6]]
Original array is not changed here.
Example with ravel()
# Creating NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Using ravel()
ravel_arr = arr.ravel()
ravel_arr[0] = 99
# Printing arrays
print("Raveled Array (view):", ravel_arr)
print("Original Array after ravel():\n", arr)
Output:
Raveled Array (view): [99 2 3 4 5 6]
Original Array after ravel():
[[99 2 3]
[ 4 5 6]]
Changes reflect in the original array because ravel()
creates a view (where possible).
3. Manipulating Dimensions (np.expand_dims() and np.squeeze())
Sometimes you need to explicitly add or remove single-dimensional entries to arrays. NumPy provides two useful methods for this:
np.expand_dims() (Add Dimensions)
This method inserts a new dimension at a specified position.
Syntax:
numpy.expand_dims(array, axis)
array: Original array.
axis: The value of axis is an integer that indicates the index where the new dimension will be added. The valid range for axis depends on the number of dimensions in the input array. For an array with n dimensions, axis can be any integer from 0 to n (inclusive).
Example:
arr = np.array([1, 2, 3])
print("Original shape:", arr.shape)
# Add a new dimension at axis 0
expanded_arr = np.expand_dims(arr, axis=0)
print("Expanded shape (axis=0):", expanded_arr.shape)
# Add another dimension at axis 1
expanded_arr2 = np.expand_dims(arr, axis=1)
print("Expanded shape (axis=1):", expanded_arr2.shape)
Output:
Original shape: (3,)
Expanded shape (axis=0): (1, 3)
Expanded shape (axis=1): (3, 1)
np.squeeze() (Remove Dimensions)
This method removes dimensions of size 1 from an array.
Syntax:
numpy.squeeze(array, axis=None)
array: Original array.
axis: Optional. Specify a particular dimension to squeeze. If omitted, it removes all single-dimensional entries.
Example:
arr = np.array([[[1], [2], [3]]])
print("Original shape:", arr.shape)
squeezed_arr = np.squeeze(arr)
print("Squeezed shape:", squeezed_arr.shape)
Output:
Original shape: (1, 3, 1)
Squeezed shape: (3,)
4. Additional Dimension Functions (np.newaxis)
You can also add new axes conveniently using NumPy’s special keyword np.newaxis
. This works similar to np.expand_dims()
but with cleaner syntax.
Example:
arr = np.array([1, 2, 3])
# Using np.newaxis to add dimension at axis 0
arr_row = arr[np.newaxis, :]
print("Row vector shape:", arr_row.shape)
# Using np.newaxis to add dimension at axis 1
arr_col = arr[:, np.newaxis]
print("Column vector shape:", arr_col.shape)
Output:
Row vector shape: (1, 3)
Column vector shape: (3, 1)
Summary Table
Function/Method | Description | Returns Copy or View? |
---|---|---|
reshape() | Changes shape of array | View (when possible) |
flatten() | Converts array to 1D (copy) | Copy |
ravel() | Converts array to 1D (view) | View (when possible) |
expand_dims() | Adds new dimensions (axes) | View |
squeeze() | Removes dimensions of size 1 | View |
np.newaxis | Adds dimensions easily | View |