1

I would like to apply a function to every element of a numpy.ndarray, something like this:

import numpy
import math

a = numpy.arange(10).reshape(2,5)
b = map(math.sin, a)
print b

but this gives:

TypeError: only length-1 arrays can be converted to Python scalars

I know I can do this:

import numpy
import math
a = numpy.arange(10).reshape(2,5)

def recursive_map(function, value):
    if isinstance(value, (list, numpy.ndarray)):
        out = numpy.array(map(lambda x: recursive_map(function, x), value))
    else:
        out = function(value)
    return out
c = recursive_map(math.sin, a)
print c

My question is: is there a built-in function or method to do this? It seems elementary, but I haven't been able to find it. I am using Python 2.7.

Kathirmani Sukumar
  • 10,445
  • 5
  • 33
  • 34
boudewijn21
  • 338
  • 1
  • 9
  • 1
    You might want to look into this question http://stackoverflow.com/questions/7701429/efficient-evaluation-of-a-function-at-every-cell-of-a-numpy-array – Konstantin May 19 '15 at 15:56

1 Answers1

5

Use np.sin it works element wise on ndarray already.

You can also reshape to a 1D array and the native map should just work. Then you can use reshape again to restore the original dimensions.

You can also use np.vectorize to write functions that can work like np.sin.

b4hand
  • 9,550
  • 4
  • 44
  • 49
  • 2
    [Relevant link](http://docs.scipy.org/doc/numpy/reference/ufuncs.html) about ufuncs in numpy – Konstantin May 19 '15 at 15:55
  • Note that the `map` and `np.vectorize` options are much, much slower than using NumPy builtins. – user2357112 May 19 '15 at 17:22
  • 1
    Now that I know what to look for: for the difference between `np.vectorize` and `np.frompyfunc`: see [this question](http://stackoverflow.com/questions/6768245/difference-between-frompyfunc-and-vectorize-in-numpy) – boudewijn21 May 20 '15 at 08:02