Say I have an array of d dimensions, and I want to apply a function which returns a 1D array to each element, yielding a d+1-dimensional array. Very much as an embedding lookup works. For instance:
def f(x):
return np.array([x * i for i in range(6)])
m = np.random.randint(0,10, (2,3,4,5))
g = np.vectorize(f)
h = np.vectorize(f, otypes=[np.ndarray])
I expect n=g(m) to have shape (2,3,4,5,6) just as if I had written 4 for loops, applying f to each element in m.
However, g raises an error: ValueError: setting an array element with a sequence. and h returns an odd array ending like:
...
[array([0, 9, 18, 27, 36, 45, 54, 63, 72]),
array([0, 5, 10, 15, 20, 25, 30, 35, 40]),
array([0, 7, 14, 21, 28, 35, 42, 49, 56]), ...,
array([0, 1, 2, 3, 4, 5, 6, 7, 8]),
array([0, 4, 8, 12, 16, 20, 24, 28, 32]),
array([0, 3, 6, 9, 12, 15, 18, 21, 24])]]]], dtype=object)
which I can't change to what I expect.
I get @hpaulj's comment, I just can't find how to do otherwise.
freturns an array for a scalarx. Creates a result array of shape matchingx. It can only put the array in anobjectdtype array.forloops?vectorizeiterates on elements ofx; it just hides that. It's slower than an explicit loop.vectorize?