6

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.

2
  • vectorize is 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. Commented Feb 17, 2018 at 23:11
  • If you wan't to achieve significant speedups have a look at numba.pydata.org/numba-doc/dev/reference/… If you are looping on an array about a speedup of a factor of 100 can usually be observed. Commented Feb 18, 2018 at 17:47

1 Answer 1

6

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:

Most efficient way to map function over numpy array

Sign up to request clarification or add additional context in comments.

4 Comments

No need for vectorize(), just call f(x), it's automatic.
@liliscent Updated my answer to show a case where vectorize is required.
@Owen683 If this answered your question, please accept as an accepted answer.
@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..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.