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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Relevant link about ufuncs in numpy
Note that the map and np.vectorize options are much, much slower than using NumPy builtins.
Now that I know what to look for: for the difference between np.vectorize and np.frompyfunc: see this question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.