[Numpy-discussion] slices vs. range() over a certain axis

Robert Kern robert.kern at gmail.com
Sat Nov 15 04:32:14 EST 2008


On Fri, Nov 14, 2008 at 22:40, David Warde-Farley <dwf at cs.toronto.edu> wrote:
> I'm trying to clarify my understanding of how slicing works and how it
> differs from specifying a sequence of indices. My question is best
> illustrated by an example:
>
>        In [278]: x = zeros((5,50))
>
>        In [279]: y = random_integers(5,size=50)-1
>
> The behaviour that I want is produced by:
>
>        In [280]: x[y,range(50)] = 1
>
> Why doesn't
>
>        In [281]: x[y,0:50] = 1
>
> produce the same effect? Is there a way to do what I am attempting in
> [280] with slicing?

The reasoning is a bit clearer with __getitem__ rather than
__setitem__. When the subscript is only a set of slices, then the
resulting array is a view. Slices specify a subarray with homogeneous
strides like any other array.

Fancy indices don't. The result must, in general, be a copy because we
will be pulling items scattered across memory in no necessary order.
Fancy indexing needs to have separate semantics. Specifically,
broadcast the index arrays then create a new array of the broadcasted
shape with elements found by iterating over the broadcasted index
arrays.

Now the question is, what do we do when we combine the two into one
subscript. Instead of reinterpreting the slices as lists and shoving
them into the fancy indexing semantics, we leave them as slices. The
procedure for fancy indexing changes slightly. We do the same
broadcasting *just* for the actual fancy indices. However, the "item"
that gets placed into each position in the output array is no longer a
scalar, but rather the result of the remaining slices. This gives us
more capabilities than interpreting a slice as the equivalent range()
since you can always just use the range().

Clear as mud?

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list