Previous topic

numpy.broadcast_arrays

Next topic

numpy.squeeze

numpy.expand_dims

numpy.expand_dims(a, axis)[source]

Expand the shape of an array.

Insert a new axis, corresponding to a given position in the array shape.

Parameters:

a : array_like

Input array.

axis : int

Position (amongst axes) where new axis is to be inserted.

Returns:

res : ndarray

Output array. The number of dimensions is one greater than that of the input array.

Examples

>>> x = np.array([1,2])
>>> x.shape
(2,)

The following is equivalent to x[np.newaxis,:] or x[np.newaxis]:

>>> y = np.expand_dims(x, axis=0)
>>> y
array([[1, 2]])
>>> y.shape
(1, 2)
>>> y = np.expand_dims(x, axis=1)  # Equivalent to x[:,newaxis]
>>> y
array([[1],
       [2]])
>>> y.shape
(2, 1)

Note that some examples may use None instead of np.newaxis. These are the same objects:

>>> np.newaxis is None
True