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

Tim Michelsen timmichelsen@gmx-topmail...
Thu Dec 4 16:19:04 CST 2008


>> 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



More information about the Numpy-discussion mailing list