The Wayback Machine - https://web.archive.org/web/20230512160512/https://www.geeksforgeeks.org/insert-a-new-axis-within-a-numpy-array/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Insert a new axis within a NumPy array

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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




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)

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




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

Output: 

(3, 1, 4)

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

Python3




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)

Output: 

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

My Personal Notes arrow_drop_up
Last Updated : 29 Aug, 2020
Like Article
Save Article
Similar Reads
Related Tutorials