Reputation: 8816
Why doesn't np.newaxis
always append the axis where I put it? See example:
import numpy as np
M = np.array([[1,4],[2,5], [3,4]])
M[:,np.newaxis].shape
# returns (3, 1, 2)
Upvotes: 0
Views: 426
Reputation: 176998
According to the documents describing newaxis
:
The added dimension is the position of the newaxis object in the selection tuple.
In your example, newaxis
is in the second position of the tuple, hence the new dimension of length 1 is inserted there.
This is analogous to selecting a value at a particular index. For a three-dimensional A
, you would use A[:,0]
to retrieve the index 0
value from the second axis, not the third axis.
If you want to add the new axis in the last position of the tuple, you could write M[:,:,np.newaxis]
or alternatively use the ellipses notation:
>>> M[...,np.newaxis].shape
(3, 2, 1)
Upvotes: 2