[Numpy-discussion] Slicing with index lists

Bernhard Voigt bernhard.voigt at gmail.com
Thu Apr 12 04:35:01 EDT 2007


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

I tried:

In [97]: a[[1,3,4],[0,2]]
---------------------------------------------------------------------------
exceptions.ValueError                                Traceback (most recent
call last)

ValueError: shape mismatch: objects cannot be broadcast to a single shape

Thanks for help! Bernhard
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20070412/7a7742d5/attachment.html>


More information about the NumPy-Discussion mailing list