Using Numpy Vectorize on Functions that Return Vectors Using Numpy Vectorize on Functions that Return Vectors python python

Using Numpy Vectorize on Functions that Return Vectors


np.vectorize is just a convenience function. It doesn't actually make code run any faster. If it isn't convenient to use np.vectorize, simply write your own function that works as you wish.

The purpose of np.vectorize is to transform functions which are not numpy-aware (e.g. take floats as input and return floats as output) into functions that can operate on (and return) numpy arrays.

Your function f is already numpy-aware -- it uses a numpy array in its definition and returns a numpy array. So np.vectorize is not a good fit for your use case.

The solution therefore is just to roll your own function f that works the way you desire.


A new parameter signature in 1.12.0 does exactly what you what.

def f(x):    return x * np.array([1,1,1,1,1], dtype=np.float32)g = np.vectorize(f, signature='()->(n)')

Then g(np.arange(4)).shape will give (4L, 5L).

Here the signature of f is specified. The (n) is the shape of the return value, and the () is the shape of the parameter which is scalar. And the parameters can be arrays too. For more complex signatures, see Generalized Universal Function API.


import numpy as npdef f(x):    return x * np.array([1,1,1,1,1], dtype=np.float32)g = np.vectorize(f, otypes=[np.ndarray])a = np.arange(4)b = g(a)b = np.array(b.tolist())print(b)#b.shape = (4,5)c = np.ones((2,3,4))d = g(c)d = np.array(d.tolist())print(d)#d.shape = (2,3,4,5)

This should fix the problem and it will work regardless of what size your input is. "map" only works for one dimentional inputs. Using ".tolist()" and creating a new ndarray solves the problem more completely and nicely(I believe). Hope this helps.