简体   繁体   中英

Is there a built-in method or function to map a function on a numpy.ndarray?

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM