NumArray array-indexing

Peter Otten __peter__ at web.de
Mon Aug 16 13:47:20 CEST 2004


Michael Drumheller wrote:

> array-indexing.  Here's the basic situation: Given a rank-2 array
> (i.e., a matrix) it seems to be trivial, with array indexing,
> to extract a subset of its columns.  But it does not seem
> to be trivial to extract a subset of its rows.  The code

Could it be you are looking for the Ellipsis (...)?

>>> a = numarray.array(range(9), shape=[3,3])
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

>>> a[0:2]
array([[0, 1, 2],
       [3, 4, 5]])
>>> a[..., 1]
array([1, 4, 7])
>>> a[..., 1:]
array([[1, 2],
       [4, 5],
       [7, 8]])
>>> a[..., 0:3:2]
array([[0, 2],
       [3, 5],
       [6, 8]])

Of course in 2D you do not really need it:

>>> a[:, :2]
array([[0, 1],
       [3, 4],
       [6, 7]])


But at some point it may make things clearer:

>>> a = numarray.array(range(2**10), shape=[2]*10)
>>> a[...,:][(-1,)*7]
array([[[1016, 1017],
        [1018, 1019]],

       [[1020, 1021],
        [1022, 1023]]])

Peter




More information about the Python-list mailing list