How does numpy newaxis work and when to use it

5.0K    Asked by AyushiKhatri in Salesforce , Asked on Apr 16, 2021

I'm trying to use

numpy.newaxis

 and the result gives me a 2-d plot frame with x-axis from 0 to 1. 

However, when I try using numpy.newaxis to slice a vector,

vector[0:4,]

[ 0.04965172  0.04979645  0.04994022  0.05008303]

vector[:, np.newaxis][0:4,]

[[ 0.04965172]

[ 0.04979645]

[ 0.04994022]

[ 0.05008303]]

Is it the same thing except that it changes a row vector to a column vector?

Generally, what is the use of numpy.newaxis and in which circumstances should we use it?

Answered by Carl Paige

newaxis is also called as a pseudo-index that allows the temporary addition of an axis into a multiarray.

np.newaxis uses the slicing operator to recreate the array while numpy. reshape reshapes the array to the desired layout (assuming that the dimensions match; And this is must for a reshape to happen).

The np.newaxis is generally used with slicing. It indicates that you want to add an additional dimension to the array.

The position of the np.newaxis represents where I want to add dimensions.

>>> import numpy as np
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> a.shape
(10,)

In the first example I use all elements from the first dimension and add a second dimension:

>>> a[:, np.newaxis]
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])
>>> a[:, np.newaxis].shape
(10, 1)
The second example adds a dimension as first dimension and then uses all elements from the first dimension of the original array as elements in the second dimension of the result array:
>>> a[np.newaxis, # The output has 2 [] pairs!
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
>>> a[np.newaxis, .shape
(1, 10)

Similarly you can use multiple np.newaxis to add multiple dimensions:

>>> a[np.newaxis, :, np.newaxis]  # note the 3 [] pairs in the output
array([[[0],
        [1],
        [2],
        [3],
        [4],
        [5],
        [6],
        [7],
        [8],
        [9]]])
>>> a[np.newaxis, :, np.newaxis].shape
(1, 10, 1)


Your Answer

Interviews

Parent Categories