Is there a way to add a variable number of singleton dimensions to a numpy array? I want something like atleast_2d but for an arbitrary number of dimensions. expand_dims comes up a lot, but only adds a single dimension.
The only way I know to do this is to compute the shape first and apply it, i.e.
import numpy as np
def atleast_kd(array, k):
array = np.asarray(array)
new_shape = array.shape + (1,) * (k - array.ndim)
return array.reshape(new_shape)
expand_dimsdoes:a.reshape(shape[:axis] + (1,) + shape[axis:])expand_dimsdoesn't do anything better.