Insert a new axis within a NumPy array

This post deals with the ways to increase the dimension of an array in NumPy. NumPy provides us with two different built-in functions to increase the dimension of an array i.e.,
 

1D array will become 2D array
2D array will become 3D array
3D array will become 4D array
4D array will become 5D array

Method 1: Using numpy.newaxis()
The first method is to use numpy.newaxis object. This object is equivalent to use None as a parameter while declaring the array. The trick is to use the numpy.newaxis object as a parameter at the index location in which you want to add the new axis.
Example: 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

import numpy as np
  
  
arr = np.arange(5*5).reshape(5, 5)
print(arr.shape)
  
# promoting 2D array to a 5D array
# arr[None, ..., None, None]
arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]
  
print(arr_5D.shape)

chevron_right


Output: 

(5, 5)
(1, 5, 5, 1, 1)

Method 2: Using numpy.expand_dims()



The second method is to use numpy.expand_dims() function that has an intuitive axis kwarg. This function takes two parameters. The first is the array of which you want to increase the dimension of and the second is index/indexes of array on which you want to create a new axis.
Example: 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

import numpy as np
  
  
x = np.zeros((3, 4))
y = np.expand_dims(x, axis=1).shape
print(y)

chevron_right


Output: 

(3, 1, 4)

Example 2: Simultaneously insert many new axes in the array.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

import numpy as np
  
  
arr = np.arange(5*5).reshape(5,5)
print(arr.shape)
  
newaxes = (0, 3, -1)
arr_5D = np.expand_dims(arr, axis=newaxes)
print(arr_5D.shape)

chevron_right


Output: 

(5, 5)
(1, 5, 5, 1, 1)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.