[Numpy-discussion] Slicing/selection in multiple dimensions simultaneously

Robert Kern robert.kern@gmail....
Tue Sep 11 17:24:17 CDT 2007


Mike Ressler wrote:
> The following seems to be a wart: is it expected?
> 
> Set up a 10x10 array and some indexing arrays:
> 
> a=arange(100)
> a.shape=(10,10)
> q=array([0,2,4,6,8])
> r=array([0,5])
> 
> Suppose I want to extract only the "even" numbered rows from a - then
> 
> print a[q,:]
> 
> <works - output deleted>
> 
> Every fifth column:
> 
> print a[:,r]
> 
> <works - output deleted>
> 
> Only the even rows of every fifth column:
> 
> print a[q,r]
> 
> ---------------------------------------------------------------------------
> <type 'exceptions.ValueError'>            Traceback (most recent call last)
> 
> /.../.../.../<ipython console> in <module>()
> 
> <type 'exceptions.ValueError'>: shape mismatch: objects cannot be
> broadcast to a single shape
> 
> But, this works:
> 
> print a[q,:][:,r]
> 
> [[ 0  5]
>  [20 25]
>  [40 45]
>  [60 65]
>  [80 85]]
> 
> So why does the a[q,r] form have problems? Thanks for your insights.

It is intended that the form a[q,r] be the general case: q and r are broadcasted
against each other to a single shape. The result of the indexing is an array of
that broadcasted shape with elements found by using each pair of elements in the
broadcasted q and r arrays as indices.

There are operations you can express with this form that you couldn't if the
behavior that you expected were the case whereas you can get the result you want
relatively straightforwardly.

In [6]: a[q[:,newaxis], r]
Out[6]:
array([[ 0,  5],
       [20, 25],
       [40, 45],
       [60, 65],
       [80, 85]])


-- 
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