General Numerical Python question

Scott Ransom ransom at physics.mcgill.ca
Thu Oct 16 12:58:53 EDT 2003


larix_occidentalis at yahoo.com (Western Larch) wrote in message news:<6869c57c.0310151854.1450d5b1 at posting.google.com>...
> Michael Ressler <ressler at cheetah.jpl.nasa.gov> wrote:
> 
> [...]
> > 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.

It's actually quite easy (and much more readable IMHO) as a one liner:

> from Numeric import *
> from umath import fabs, sqrt
> a = array([1.,2.,-3.,4.,-5.,6.,-7.,-8.,9.])
> a = where(a<0, sqrt(fabs(a)), a)

That's it!
 
> In the Octave programming language (Matlab-like), the operation
> is called "find" -- find(a<0) returns the indices of the negative
> elements; a(find(a<0)) returns the negative elements themselves.

A similar operation is possible in Numeric:

compress(a<0, a) returns the elements of a that have a<0.

> With all due respect, Octave rocks pretty hard, and although I
> love Python I've only fiddled around with Numeric Python a little
> bit -- I haven't found any reason to prefer it to Octave.

Numeric is wonderful as well.  And one of the biggest benefits is that
you get all of the power of Python (and its _huge_ standard and
contributed libraries) as a bonus.

Scott




More information about the Python-list mailing list