I often find myself to broadcast 1d arrays into a specific dimension dim_a given a total number of dimension dim_total. What I mean is the following:
import numpy as np
a = np.arange(10)
dim_a = 2
dim_total = 4
shape = tuple([-1 if idx == dim_a else 1 for idx in range(dim_total)])
print(a.reshape(shape))
axis = list(range(dim_total))
del axis[dim_a]
print(np.expand_dims(a, axis=axis))
Both work as expected, however the question is whether there is an even shorter way to achieve this for a single array?
expand_dimssource code to see how it creates thereshapeparameter.reshape, but a bit more work to use your particular mix of inputs.ato a(1,1,10,1)shape. For many broadcasting operations it would be sufficient to expand it to(10,1), with the leading dimensions added automatically as needed.keepdims=Trueand only on the final result squeeze the empty axes.