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.

Owen683
  • 137
  • 1
  • 1
  • 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 Answers1

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

user3483203
  • 50,081
  • 9
  • 65
  • 94