Numpy [...,None]
The slice of [..., None]
consists of two "shortcuts":
The ellipsis literal component:
The dots (...) represent as many colons as needed to produce a complete indexing tuple. For example, if x is a rank 5 array (i.e., it has 5 axes), then
x[1,2,...]
is equivalent tox[1,2,:,:,:]
,x[...,3]
tox[:,:,:,:,3]
andx[4,...,5,:]
tox[4,:,:,5,:]
.
(Source)
The None
component:
numpy.newaxis
The
newaxis
object can be used in all slicing operations to create an axis of length one.newaxis
is an alias for ‘None’, and ‘None’ can be used in place of this with the same result.
(Source)
So, arr[..., None]
takes an array of dimension N
and "adds" a dimension "at the end" for a resulting array of dimension N+1
.
Example:
import numpy as npx = np.array([[1,2,3],[4,5,6]])print(x.shape) # (2, 3)y = x[...,None]print(y.shape) # (2, 3, 1)z = x[:,:,np.newaxis]print(z.shape) # (2, 3, 1)a = np.expand_dims(x, axis=-1)print(a.shape) # (2, 3, 1)print((y == z).all()) # Trueprint((y == a).all()) # True
Consider this code:
np.ones(shape=(2,3))[...,None].shape
As you see the 'None' phrase change the (2,3) matrix to a (2,3,1) tensor. As a matter of fact it put the matrix in the LAST index of the tensor.
If you use
np.ones(shape=(2,3))[None, ...].shape
it put the matrix in the FIRST index of the tensor