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.
Asked
Active
Viewed 1.2k times
6
-
`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. – hpaulj Feb 17 '18 at 23:11
-
If you wan't to achieve significant speedups have a look at http://numba.pydata.org/numba-doc/dev/reference/jit-compilation.html#vectorized-functions-ufuncs-and-dufuncs If you are looping on an array about a speedup of a factor of 100 can usually be observed. – max9111 Feb 18 '18 at 17:47
1 Answers
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:

user3483203
- 50,081
- 9
- 65
- 94
-
-
@liliscent Updated my answer to show a case where `vectorize` is required. – user3483203 Feb 17 '18 at 22:21
-
@Owen683 If this answered your question, please accept as an accepted answer. – user3483203 Feb 17 '18 at 22:22
-
@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.. – llllllllll Feb 17 '18 at 22:31