Sunday, October 6, 2024
Google search engine
HomeLanguagesInsert a new axis within a NumPy array

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




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)

RELATED ARTICLES

Most Popular

Recent Comments