Useful "np.vectorize" function to match arrayfun in Matlab

In Matlab it is convenient to use arrayfun to map the function to a data array.
Today I just find it out that we have the analogous one in Python. 




So if you want to do in Matlab :   arrayfun( @(x) x*x, [1:10])
Then you can do it in Python : 
a = np.arange(1,10)
np.vectorize(lambda x: x*x),(a)
Alternatively you can do it in R:  sapply(seq(1,10), function(x){x*x})


But please note that np.vectorize is designed for convenience, not for performance. 
So essentially you are still doing in a loop which may slow.


Also there is one called "np.fromiter". 
As defined in manual, it is used for "Create a new 1-dimensional array from an iterable object."
iterable = (x*x for x in range(1,10))
np.fromiter(iterable, float)
Don't forget the map function which is very useful too.
list(map((lambda x: x*x), a))

Ok, come back to np.vectorize, several Parameters are useful :


(1)excluded: 
Since there may be more that one arguments, so it is possible to use 
excluded parameter to define which argument not need to be vectorized. 


def mytest(a1, b1):
    return np.sum(a1)*b1
pp = np.vectorize(mytest); print(pp([1,2,5],[3,4,2]))  # [3 8 6]
# so here, we don't vectorize the first item, so np.sum takes action!
pp.excluded.add(0); print(pp([1,2,5],[3,4,2]))          # [24 32 16]  

# # don't know why the following one does not work!               
pp2 = np.vectorize(mytest, excluded=['a1']); print(pp2([1,2,3],[3,4,2])) 



(2)signature:
convolve_b = np.vectorize(np.convolve,signature='(n),(m)->(k)')
print(convolve_b(np.eye(4),[1,2,1])) 
[[ 1.  2.  1.  0.  0.  0.]
 [ 0.  1.  2.  1.  0.  0.]
 [ 0.  0.  1.  2.  1.  0.]
 [ 0.  0.  0.  1.  2.  1.]]

留言