Tsallaka zuwa abun ciki
Justice Tech School

Adding Axes

np.newaxis or None adds a length 1 dimension. expand_dims and squeeze add and remove them.

Example
import numpy as np
a = np.array([1, 2, 3])
print(a.shape, a[:, np.newaxis].shape, a[None, :].shape)
print(np.expand_dims(a, 0).shape)
print(np.squeeze(np.ones((1, 3, 1))).shape)

Result

(3,) (3, 1) (1, 3)
(1, 3)
(3,)

Exercise

Remove length 1 axes.

np.(x)

Quiz Test

What does a[:, None] make?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.