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
.