[Numpy-discussion] Speedup a code using apply_along_axis

Xavier Gnata xavier.gnata@gmail....
Sun Feb 28 12:51:59 CST 2010


Hi,

I'm sure I reinventing the wheel with the following code:
from numpy import *
from scipy import polyfit,stats

def f(x,y,z):
    return x+y+z
M=fromfunction(f,(2000,2000,10))

def foo(M):
    ramp=where(M<1000)[0]
    l=len(ramp)
    t=arange(l)
    if(l>1):
        return polyfit(t,ramp,1)[0]
    else:
        return 0

print apply_along_axis(foo,2,M)


In real life M is not the result of one fromfunction call but it does
not matter.
The basic idea is to compute the slope (and only the slope) along one
axis of 3D array.
Only the values below a given threshold should be taken into account.

The current code is ugly and slow.
How to remove the len and the if statement?
How to rewrite the code in a numpy oriented way?

Xavier



More information about the NumPy-Discussion mailing list