Matt Feinstein wrote: > Is there an optimal way to apply a function to the elements of a two-d > array? > > What I'd like to do is define some function: > > def plone(x): > return x+1 > > and then apply it elementwise to a 2-D numarray. I intend to treat the > function as a variable, so ufuncs are probably not appropriate-- I > realize that what I'm looking for won't be terrifically efficient, > but I'd like to avoid doing it in the -worst- possible way. > > Some things I've looked at include things like > > def applyfun(m,f): > elist = [f(e) for e in m] > return reshape(elist,m.shape) > > however, I can see that this looks neat but probably generates several > copies of the array, which is not so neat. > > Is there a better way?
I must be missing something, because the simplest possible thing seems to work for me: py> import numarray as na py> def plus1(arr): ... return arr + 1 ... py> def apply_func(arr, f): ... return f(arr) ... py> a = na.arange(20, shape=(4, 5)) py> a array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) py> apply_func(a, plus1) array([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]) Is this not what you wanted? STeVe -- http://mail.python.org/mailman/listinfo/python-list