w3resource

NumPy: Insert a new axis within a 2-D array


Insert New Axis in 2D Array

Write a NumPy program to insert a new axis within a 2-D array.
2-D array of shape (3, 4).
New shape will be will be (3, 1, 4).

Pictorial Presentation:

Python NumPy: Insert a new axis within a 2-D array

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 3x4 array of zeros
x = np.zeros((3, 4))

# Expanding the dimensions of the array x along axis 1 and storing the shape of the result in y
y = np.expand_dims(x, axis=1).shape

# Printing the shape of the expanded array
print(y)

Sample Output:

(3, 1, 4)

Explanation:

In the above code –

x = np.zeros((3, 4)): This line creates a 2D array x with shape (3, 4) filled with zeros.

y = np.expand_dims(x, axis=1).shape: The np.expand_dims() function takes the input array x and adds a new axis along the specified axis, in this case, axis=1. The original shape of x is (3, 4), and after expanding the dimensions, the new shape becomes (3, 1, 4).

print(y): Here print(y) prints the shape of the newly expanded array, which is (3, 1, 4).

Python-Numpy Code Editor: