Apply a function to an array elementwise
![](https://secure.gravatar.com/avatar/37bc5c7a088254ecb029fc17ee922679.jpg?s=120&d=mm&r=g)
Hi I want to apply a function (myfunc which takes and returns a scalar) to each element in a multi-dimensioned array (data): I can do this: newdata = numpy.array([myfunc(d) for d in data.flat]).reshape(data.shape) But I'm wondering if there's a faster more numpy way. I've looked at the vectorize function but can't work it out. thanks Eleanor -- View this message in context: http://www.nabble.com/Apply-a-function-to-an-array-elementwise-tp20823768p20... Sent from the Numpy-discussion mailing list archive at Nabble.com.
![](https://secure.gravatar.com/avatar/40489da22d2dc0cc12596420bb810463.jpg?s=120&d=mm&r=g)
Elfnor wrote:
Hi
I want to apply a function (myfunc which takes and returns a scalar) to each element in a multi-dimensioned array (data):
I can do this:
newdata = numpy.array([myfunc(d) for d in data.flat]).reshape(data.shape)
But I'm wondering if there's a faster more numpy way. I've looked at the vectorize function but can't work it out.
from numpy import vectorize new_func = vectorize(myfunc) newdata = new_func(data) Should work. -Travis
![](https://secure.gravatar.com/avatar/6f3cb304671ae5b6ea04dfe0e7948651.jpg?s=120&d=mm&r=g)
I want to apply a function (myfunc which takes and returns a scalar) to each element in a multi-dimensioned array (data):
I can do this:
newdata = numpy.array([myfunc(d) for d in data.flat]).reshape(data.shape)
But I'm wondering if there's a faster more numpy way. I've looked at the vectorize function but can't work it out.
from numpy import vectorize
new_func = vectorize(myfunc) newdata = new_func(data) This seems be some sort of FAQ. Maybe the term vectorize is not known to all (newbie) users. At least finding its application in the docs doesn't seem easy.
Here a more threads: * optimising single value functions for array calculations - http://article.gmane.org/gmane.comp.python.numeric.general/26543 * vectorized function inside a class - http://article.gmane.org/gmane.comp.python.numeric.general/16438 Most newcomers learn at some point to develop functions for single values (scalars) but to connect this with computation of full array and be efficient is another step. Some short note has been written on the cookbook: http://www.scipy.org/Cookbook/Autovectorize Regards, Timmie
participants (3)
-
Elfnor
-
Tim Michelsen
-
Travis Oliphant