[Numpy-discussion] Apply a function to an array elementwise

Travis Oliphant oliphant@enthought....
Wed Dec 3 20:22:01 CST 2008

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.


More information about the Numpy-discussion mailing list