[Numpy-discussion] Fancy indexing question:

Robert Kern robert.kern at gmail.com
Tue Feb 24 14:43:49 EST 2009


On Tue, Feb 24, 2009 at 13:39, Christopher Barker <Chris.Barker at noaa.gov> wrote:
> HI all,
>
> I'm having a bit of trouble getting fancy indexing to do what I want.
>
> Say I have a 2-d array:
>
>  >>> a
> array([[ 0,  1,  2,  3],
>        [ 4,  5,  6,  7],
>        [ 8,  9, 10, 11],
>        [12, 13, 14, 15],
>        [16, 17, 18, 19],
>        [20, 21, 22, 23]])
>
> I want to extract a sub-array:
>
> The 1st, 3rd, and 4th rows:
>  >>> i
> [1, 3, 4]
>
> and the 1st and 3rd columns:
>  >>> j
> [1, 3]
>
> so I should get a 3x2 array:
>
> [[ 5,  7],
>  [13, 15],
>  [17, 19]]
>
> The obvious (to me!) way to do this:
>
>  >>> a[i,j]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ValueError: shape mismatch: objects cannot be broadcast to a single shape
>
> fails.

Please read the documentation:

  http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

The short answer is that in multidimensional fancy indexing, the index
arrays are broadcasted against each other first, then the result array
is found by iterating over the broadcasted arrays in parallel. The
result array is the same shape as the broadcasted shape of the inde

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