Learn how to add dimensions to NumPy arrays using np.newaxis and np.expand_dims() functions for reshaping multidimensional data in Python.

NumPy provides multiple methods to expand array dimensions, essential for data preprocessing, machine learning, and broadcasting operations.
How to Add Dimensions to NumPy Arrays Using np.newaxis
import numpy as np
my_array = np.arange(6).reshape(3, 2)
print(f"My array shape is: \n {my_array.shape}")
my_expanded_array = my_array[:, np.newaxis, :, np.newaxis]
print(f"My expanded array shape is: \n {my_expanded_array.shape}")
I am using the newaxis function and adding it as a parameter exactly where I can add a new axis.
My array shape is: (3, 2) My expanded array shape is: (3, 1, 2, 1)
This is how to add dimensions at the beginning of the Numpy array.
import numpy as np
my_array = np.arange(6).reshape(3, 2)
print(f"My array shape is: \n {my_array.shape}")
my_expanded_array = my_array[:, np.newaxis, :, np.newaxis]
print(f"My expanded array shape is: \n {my_expanded_array.shape}")
my_another_array = my_array[:, :, np.newaxis, np.newaxis]
print(f"My another expanded array shape is: \n {my_another_array.shape}")
Using consecutive np.newaxis parameters adds multiple dimensions sequentially; my_array[:, :, np.newaxis, np.newaxis] appends two new dimensions at the end.
My array shape is: (3, 2) My expanded array shape is: (3, 1, 2, 1) My another expanded array shape is: (3, 2, 1, 1)
How to Add Dimensions Using NumPy’s expand_dims() Function
The syntax my_array[:, np.newaxis, :] adds a new dimension of size 1 at the specified position, creating shape (3, 1, 2) from (3, 2).
The easiest example is to tell Numpy where to add a dimension to an array as a parameter.
import numpy as np
my_array = np.arange(6).reshape(3, 2)
print(f"My array shape is: \n {my_array.shape}")
my_expand_dims_array = np.expand_dims(my_array, axis=2)
print(f"My expand dims array shape is: \n {my_expand_dims_array.shape}")
I wrote np.expand_dims(my_array, axis=2) to add the axis as a third dimension.
My array shape is: (3, 2) My expand dims array shape is: (3, 2, 1)
There is also the possibility to add multiple axes with expand_dims. To add multiple dimensions to a Numpy array, just use tuple values as the expand_dims parameter.
import numpy as np
my_array = np.arange(6).reshape(3, 2)
print(f"My array shape is: \n {my_array.shape}")
my_expand_dims_array = np.expand_dims(my_array, axis=2)
print(f"My expand dims array shape is: \n {my_expand_dims_array.shape}")
my_expand_dims_array = np.expand_dims(my_array, axis=(0, 1, 4))
print(f"My expand dims array shape is: \n {my_expand_dims_array.shape}")
I used np.expand_dims (my_array, axis= (0, 1, 4) to add the first, second, and fifth axes.
My array shape is: (3, 2) My expand dims array shape is: (3, 2, 1) My expand dims array shape is: (1, 1, 3, 2, 1)
Master NumPy dimension expansion using np.newaxis and np.expand_dims() for data preprocessing, broadcasting, and machine learning workflows.
