General Numerical Python question

2mc mcrider at bigfoot.com
Fri Oct 17 01:40:32 EDT 2003


Michael Ressler <ressler at cheetah.jpl.nasa.gov> wrote in message news:<slrnboqrh1.6mk.ressler at cheetah.jpl.nasa.gov>...
> Another example of thinking things differently is suppose you have a
> vector where the values are randomly positive or negative. Suppose for
> reasons known only to you, you want to replace the negative values
> with the sqrt of their absolute values. With Numeric, no loops are
> involved.
> 
> from Numeric import *
> a=array([1.,2.,-3.,4.,-5.,6.,-7.,-8.,9.])	# make up an array
> idx=nonzero(a<0)			# indexes of the negative values
> sqrs=sqrt(abs(take(a,idx)))		# get the sqrts of neg elements
> put(a,idx,sqrs)				# put them back into a
> print a					# works!  
> 
> You can make the whole thing a one-liner if you want to get carried
> away with it. It's too bad "nonzero" isn't called "whereis" or
> something like that - it would make the idx= line more obvious.
> 
> Mike

I think I'm finally getting a handle on this.  So, my thanks to
everyone who has so graciously helped me out with their suggestions.

How would you handle the above if "a" were a 2d array since "nonzero"
only works on 1d arrays?  Could you have used the "nonzero" function
on a "vertical" slice of the array (from the perspective of an array
of rows and columns - a vertical slice being the data in the column)?

I mostly deal with 2d arrays, but I have a few 3d arrays.  So, I'm
curious how you would handle your example above with a multdimensional
array.

Thanks.  And, thanks again to all.

Matt




More information about the Python-list mailing list