[Numpy-discussion] indexing question

Robert Kern robert.kern at gmail.com
Mon Nov 22 15:04:37 EST 2010


2010/11/21 Ernest Adrogué <eadrogue at gmx.net>:
> Hi,
>
> Suppose an array of shape (N,2,2), that is N arrays of
> shape (2,2). I want to select an element (x,y) from each one
> of the subarrays, so I get a 1-dimensional array of length
> N. For instance:
>
> In [228]: t=np.arange(8).reshape(2,2,2)
>
> In [229]: t
> Out[229]:
> array([[[0, 1],
>        [2, 3]],
>
>       [[4, 5],
>        [6, 7]]])
>
> In [230]: x=[0,1]
>
> In [231]: y=[1,1]
>
> In [232]: t[[0,1],x,y]
> Out[232]: array([1, 7])
>
> This way, I get the elements (0,1) and (1,1) which is what
> I wanted. The question is: is it possible to omit the [0,1]
> in the index?

No, but you can write generic code for it:

  t[np.arange(t.shape[0]), x, y]

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