Is there a way to map a function to every value in a numpy array easily? I've done it before by splitting it into lists, using list comprehension and remaking the matrix but it seems there must be an easier way.
1 Answer
Yes, you can use np.vectorize()
>>> import numpy as np
>>> def myfunc(a, b):
... if a > b:
... return a - b
... else:
... return a + b
...
>>> vfunc = np.vectorize(myfunc)
>>> vfunc(np.array([[1,2,3],[1,2,3]]),2)
array([[3, 4, 1],
[3, 4, 1]])
There are some cases where you do not need np.vectorize(), and you simply able to call the function using an np.array() as a parameter, like so:
>>> def add_one(x):
... return x + 1
...
>>> add_one(np.array([1,2,3,4]))
array([2, 3, 4, 5])
>>>
Much more discussion on performance and usage can be found here:
4 Comments
llllllllll
No need for
vectorize(), just call f(x), it's automatic.user3483203
@liliscent Updated my answer to show a case where
vectorize is required.user3483203
@Owen683 If this answered your question, please accept as an accepted answer.
llllllllll
@chrisz It makes sense since I find OP is asking "an easy way", not "performant way". Just as stated in your linked question,
vectorize() provides no performance gain. Upvoted..
vectorizeis easy to use - usually. But beware there have been a lot of questions about why doesn't it work - or why doesn't work faster.