Let’s check how to add a dimension to a Numpy array. We will use the newaxis and expand_dims functions.

In this Python tutorial, I’ll show a few ways to expand the Numpy array by adding another dimension.

Let’s start with the easiest way.

## Adding dimension with the newaxis method

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}")

Thanks to my_array[:, :, np.newaxis, np.newaxis] it is placed at the beginning of the array.

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)

## Adding dimension with the expand_dims method

There is also the expand_dims Numpy function when newaxis is not enough for you.

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)

For sure, you know now how to add dimensions to Numpy arrays.