Numpy expand_dims() method expands the shape of an array. The np expand_dims inserts a new axis that will appear at the axis position in the expanded array shape.
np.expand_dims
The np.expand_dims() is a mathematical library function that expands the array by inserting a new axis at the specified position. This function requires two parameters.
Syntax
np.expand_dims(arr, axis)
Parameters
arr: The arr is a required parameter, and it is an input array.
axis: Position where a new axis is to be inserted.
Example of numpy expand_dims()
See the following code.
# app.py import numpy as np x = np.array([11, 21]) print('Array x:', x) print('x shape: ', x.shape)
Output
python3 app.py Array x: [11 21] x shape: (2,)
Now, let’s expand the dimension on the x-axis. Write the following code.
# app.py import numpy as np x = np.array([11, 21]) print('Array x:', x) print('x shape: ', x.shape) y = np.expand_dims(x, axis=0) print(y) print('y shape: ', y.shape)
Output
python3 app.py Array x: [11 21] x shape: (2,) [[11 21]] y shape: (1, 2)
The y is the result of adding a new dimension to x.
From the output, you can see that we have added a new dimension on axis = 0.
# app.py import numpy as np x = np.array(([11, 21], [19, 18])) print('Array x:', x) print('\n') # insert axis at position 0 y = np.expand_dims(x, axis=0) print('Array y:') print(y) print('\n') print('The shape of X and Y array:') print(x.shape, y.shape) print('\n') # insert axis at position 1 y = np.expand_dims(x, axis=1) print('Array Y after inserting axis at position 1:') print(y) print('\n') print('x.ndim and y.ndim:') print(x.ndim, y.ndim) print('\n') print('x.shape and y.shape:') print(x.shape, y.shape)
Output
python3 app.py Array x: [[11 21] [19 18]] Array y: [[[11 21] [19 18]]] The shape of X and Y array: (2, 2) (1, 2, 2) Array Y after inserting axis at position 1: [[[11 21]] [[19 18]]] x.ndim and y.ndim: 2 3 x.shape and y.shape: (2, 2) (2, 1, 2)
In this example, we can see that using Numpy.expanded_dims() method, and we can get the expanded array using this method.
That’s it for this tutorial.