Numeric slicing, iteration prob.

Duncan Smith buzzard at
Tue Aug 6 02:00:23 CEST 2002

"Fernando Perez" <fperez528 at> wrote in message
news:aimtmj$mg2$1 at


> Can't think of a nicer one right now, but there probably is one. Maybe
> the necessary index structures and use take()? Don't know...

I considered take() for a while but it didn't look too nice (hope this is
not too technical ;-)).

The following is what I currently have to generate the appropriate slice
(self.values is a Numeric array),

def getSlice(index, axes):
    last_axis = 0
    s = 'self.values['
    for axis in axes:
        s += ':,'*(axis-last_axis-1) + str(index[axis]) + ','
        last_axis = axis

    return s + '...]'

>>> getSlice((2,3,5,6), [0,1,3])

Seems to work OK, but I'm going to be calling this function many times and
any speed ups will be of practical benefit.  Maybe I can cache previous
slices in a dictionary or something.  Typically I might want the slices
'self.values[2,:,:,6,...]' and 'self.values[2,3,...]', then subsequently
'self.values[2,3,:,6,...]'.  Hmmm?

> > On a related note, does anyone have a feeling for the most efficient way
> > checking if all the values in a returned slice are zero? I can obviously
> > just iterate over the cells and break when I get a non-zero value, but
> > hoping there's some more efficient method available in Numeric. TIA.
> Look into alltrue:
> In [14]: import Numeric as N
> In [15]: N.alltrue ?
> Type:           function
> Base Class:     <type 'function'>
> String Form:    <function alltrue at 0x82e31f4>
> Namespace:      Currently not defined in user session.
> File:
> /usr/users/fperez/local/lib/python2.2/site-packages/Numeric/
> Definition:     N.alltrue(x, axis=0)
> Docstring:
>     Perform a logical_and over the given axis.
> That may help.

Cheers.  Actually it's 'sometrue()' that seems to do the job,

def f5(table):
    if Numeric.sometrue(Numeric.ravel(table)):
        return 0
        return 1

which is (on average) fractionally quicker than using,

if Numeric.add.reduce(Numeric.ravel(table)):



> Cheers,
> f

More information about the Python-list mailing list