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).


For more Practice: Solve these Related Problems:

  • Write a NumPy program to insert a new axis into a 2D array to transform its shape using np.newaxis.
  • Convert a (3,4) array into a (3,1,4) array by inserting an axis at the appropriate position.
  • Implement a function that adds an extra axis at a specified position in a given array.
  • Use slicing with np.newaxis to reshape a 2D array into a 3D array and validate the result.

Go to:


PREV : Inputs as Arrays with 2D/3D Views
NEXT : Remove Single-Dimensional Entries


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.