Understand numpy.newaxis with Examples for Beginners – NumPy Tutorial

By | September 15, 2019

numpy.newaxis represents a new axis in numpy array, in this tutorial, we will write some examples to help you understand how to use it correctly in python application.

Feature of numpy.newaxis

  • numpy.newaxis can add a demension to numpy array.
  • you can view numpy.newaxis  = 1.

For example:

import numpy as np

x = np.array([1, 2, 3, 4])
print(x)
print(np.shape(x))

The shape of x is: (4,)

x is:

[1 2 3 4]

As to example:

x_1 = x[np.newaxis, :]
print(x_1)
print(np.shape(x_1))

x_1 shape is:(1, 4)

x_1 is:

[[1 2 3 4]]

As to example:

x_2 = x[: ,np.newaxis]
print(x_2)
print(np.shape(x_2))

x_2 shape is: (4, 1)

x_2 is:

[[1]
 [2]
 [3]
 [4]]

As to example:

x_3 = x[np.newaxis, np.newaxis, :]
print(x_3)
print(np.shape(x_3))

x_3 shape is: (1, 1, 4)

x_3 is:

[[[1 2 3 4]]]

Leave a Reply