Python

NumPy np.newaxis()

The newaxis() object in NumPy allows us to increase the dimensions of an array by adding new axes. This function is an alias for setting the None parameter during array declaration. However, let us explore various examples and use cases using the newaxis method.

Example 1

The example shown below converts a 1-dimensional array into a 2D array as shown below:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr)
new_arr = arr[np.newaxis]
print(new_arr)

The code above should convert the 1D array into a column matrix as shown below:

As mentioned, the newaxis method is very similar to using the None parameter as shown below:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr)
new_arr = arr[None]
print(new_arr)

This returns a similar value as shown below:

Example 2

What happens when you apply the newaxis on a 2D array. Take a look at the example below:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
new_arr = arr[np.newaxis]
print(new_arr)

This should return a new array as shown:

Note that you can insert more than one axis as shown:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
new_arr = arr[np.newaxis, np.newaxis]
print(new_arr)

The above code should return:

Terminating

This short article illustrates various examples of using the np.newaxis object. Check the docs to learn more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list