I have 2 arrays:
>>> a.shape
(9, 3, 11)
>>> b.shape
(9,)
I would like to compute the equivalent of c[i, j] = f(a[i, j, :], b[i]) where f(a0, b0) is a function that takes 2 parameters, with len(a0) == 11 and len(b0) == 9. Here, i is iterating on range(9) and j is iterating on range(3).
Is there a way to code this using numpy.vectorize? Or is it simpler with some clever broadcasting?
I have been trying for 2 hours and I just don't understand how to make it work... I tried to broadcast or to use signatures but to no avail.
np.array([f(a[i,j,:], b[i]) for j in range(3)] for i in range(9)]).a + b[:,None,None]will work but the result is (9,3,11). Or maybenp.sum(a + b[:,None,None]).axis=2)if you want (9,3), but then you might as wellnp.sum(a, axis=2)first.np.vectorizein default mode passes scalar values to the function. There is asignatureoption that makes it pass arrays, but it is trickier to use, and even slower.apply_along_axiscan iterate on youri,jdimensions ofa(slowly), but it can't, at the same time iterate onb. It's just a one array iterator. The nested list comprehension is probably your best option.ccan be a numeric dtype array. That requires, I assume, some sort of reduction on the size 11 dimension.np.vectorize(f, signature="(k),(1)->()")and then I have to call it likef(a, b[:, None, None]. Do you think this would be much slower than a loop?