Skip to content
Advertisement

Difference of Numpy Dimension Expand code

I got confuse between two Numpy dimension expand code.

First code is X[:, np.newaxis].

Second code is X[:, np.newaxis, :].

I ran this code on Jupyter, But it returns same shape and result.

What is the difference?

Advertisement

Answer

Refer numpy documentation for newaxis. https://numpy.org/doc/stable/reference/constants.html#numpy.newaxis

x = np.arange(3)

x[newaxis, :] is equivalent to x[newaxis] and x[None] Any dimension after np.newaxis is still present in the resulting array, even if not explicitly denoted by a slice :.

x[np.newaxis, :].shape
#(1, 3)
x[np.newaxis].shape
#(1, 3)
x[None].shape
#(1, 3)
x[:, np.newaxis].shape
#(3, 1)

Hence in your case

X[:,np.newaxis] is X[:, np.newaxis, :]
#True

PS- I think you got confused by ellipses... and np.newaxis.

X[...,np.newaxis].shape
#(10,2,1)
# newaxis is introduced after all the previous dimensions 
X[:, np.newaxis].shape
#(10,1,2)
# newaxis is introduced at 1st index or 2nd position.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement