[Numpy-discussion] Slicing with index lists

Robert Kern robert.kern at gmail.com
Thu Apr 12 04:43:19 EDT 2007


Bernhard Voigt wrote:
> Dear all!
> 
> in a 2-dim array I would like to select rows specified by a list of
> indexes and from these rows I'd like to select columns specified by
> another list of indexes. That's what I found as a solution:
> 
> In [90]: a = arange(15).reshape(5,3)
> In [91]: a
> Out[91]:
> array([[ 0,  1,  2],
>        [ 3,  4,  5],
>        [ 6,  7,  8],
>        [ 9, 10, 11],
>        [12, 13, 14]])
> 
> # select rows 1,3,4 and columns 0,2
> 
> In[92]: a[[1,3,4],:][:,[0,2]]
> Out[92]:
> array([[ 3,  5],
>        [ 9, 11],
>        [12, 14]])
> 
> Is there a better way to express this selection? I thought there might
> be single slicing expression for this, but I couldn't figure it out :-(

In [3]: from numpy import *

In [4]: a = arange(15).reshape(5,3)

In [5]: a[ix_([1,3,4], [0,2])]
Out[5]:
array([[ 3,  5],
       [ 9, 11],
       [12, 14]])

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