Is this the best way to add an extra dimension to a numpy array in one line of code?

It’s easier like this:

k.reshape(k.shape + (1,))

But if all you want is to add an empty dimension at the end, you should use numpy.newaxis:

import numpy as np
k = k[..., np.newaxis]

or

k = k[..., None]

(See the documentation on slicing).

Leave a Comment