[Numpy-discussion] Apply a function to all indices

Ernest Adrogué eadrogue@gmx....
Fri Feb 26 05:43:00 CST 2010


Hi,

26/02/10 @ 11:23 (+0100), thus spake Ole Streicher:
> Hi,
> 
> I want to apply a function to all indices of an array that fullfill a
> certain condition.
>
> What I tried:
> 
> ---------------------8<--------------------------------
> import numpy
> 
> def myfunc(x):
>     print 'myfunc of', x
> 
> a = numpy.random.random((2,3,4))
> numpy.apply_along_axis(myfunc, 0, numpy.where(a > 0.8))
> ---------------------8<--------------------------------
> 
> But this prints just the first index vector and then shows a 
> TypeError: object of type 'NoneType' has no len()
> 
> What is wrong with my code and how can I do it right?

Your function returns nothing (i.e. None), and the numpy
function was expecting a scalar or an array-like object, that's
why it fails.

It depends on what exactly you want to do. If you just want
to iterate over the array, try something liks this

for element in a[a > 0.8]:
	myfunc(element)

Or if you want to produce a different array of the same shape
as the original, then you probably need a vectorised function.

def myfunc(x):
    print 'myfunc of', x
	if x > 0.8:
	    return x + 2
	else:
	    return x
vect_func = numpy.frompyfunc(myfunc, 1, 1)
vect_func(a)

But in this case, myfunc() has to return a scalar value for
each element in a.

> Best regards
> 
> Ole
> 
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion


More information about the NumPy-Discussion mailing list