Numpy: use reshape or newaxis to add dimensions

One reason to use numpy.newaxis over ndarray.reshape is when you have more than one “unknown” dimension to operate with. So, for example, for the following array:

>>> arr.shape
(10, 5)

This works:

>>> arr[:, np.newaxis, :].shape
(10, 1, 5)

But this does not:

>>> arr.reshape(-1, 1, -1)
...
ValueError: can only specify one unknown dimension

Leave a Comment