[Numpy-discussion] Question about indexing
Travis E. Oliphant
oliphant@enthought....
Fri May 30 02:52:29 CDT 2008
Hi Raul,
There are a some points that might help you with indexing:
1) a[obj] is (basically) equivalent to a.__getitem__(numpy.index_exp[obj])
2) obj is always converted to a tuple if it isn't one already:
* numpy.index_exp[0,1] == (0,1)
* numpy.index_exp[(0,1)] == (0,1)
* numpy.index_exp[[0,1]] == ([0,1],)
3) There are two basic kinds of indexing:
a) Simple or slice-based indexing where the indexing tuple (obj)
consists of just integers, slice objects, or Ellipses and the returned
array is a "view" of the original array (no memory is copied).
b) Fancy or advanced indexing which occurs when anything else (e.g.
a list) is used in the indexing tuple and the returned array is a "copy"
of the original array for largely technical reasons.
4) If the length of the indexing tuple is smaller than the number of
dimensions in the array, the remaining un-indexed dimensions are
returned. It is equivalent to appending slice(None) to the indexing tuple.
5) For fancy indexing using lists (and nested lists) in the indexing
tuple, the shape of the array is the shape of the indexing (nested) list
plus the shape of the un-indexed dimensions.
Raul Kompass wrote:
> I systematically tried and got the follwing:
> ----------------------------------
> >>> from scipy import *
> >>> a = random.rand(10).reshape(2,5)
> >>> a
> array([[ 0.87059263, 0.76795743, 0.13844935, 0.69040701, 0.92015062],
> [ 0.97313123, 0.85822558, 0.8579044 , 0.57425782, 0.57355904]])
>
>
> >>> a[0,1] # shape([0,1]) = (2,)
> 0.767957427399
>
Equivalent to a[(0,1)] so the indexing tuple selects a single element of
the 2d array.
> >>> a[[0],[1]] # shape([[0],[1]]) = (2, 1)
> array([ 0.76795743])
>
Equivalent to a[([0], [1])] so the indexing tuple selects the same
single element of the 2d array as before except now it is a 1-d array
because fancy indexing is used [0] and [1] are lists.
> >>> a[[0,1]] # shape([[0,1]]) = (1, 2)
> array([[ 0.87059263, 0.76795743, 0.13844935, 0.69040701, 0.92015062],
> [ 0.97313123, 0.85822558, 0.8579044 , 0.57425782, 0.57355904]])
>
>
Equivalent to a[([0,1],)] so the indexing tuple is of length 1 and the
shape of the resulting array is 2-d (the indexing list is 1-d and the
un-indexed portion is 1-d). Rows 0 and 1 are selected from a.
Equivalent to stacking a[0] and a[1] on top of each other.
> >>> a[[[0,1]]] # shape([[[0,1]]]) = (1, 1, 2)
> array([[ 0.87059263, 0.76795743, 0.13844935, 0.69040701, 0.92015062],
> [ 0.97313123, 0.85822558, 0.8579044 , 0.57425782, 0.57355904]])
>
>
The shape here I can't quite explain at the moment especially because a[
[[0,1]],] is shaped differently and probably shouldn't be. It looks like
a[ <nested_list> ] has one smaller dimension than a[ <nested_list>, ]
(notice the comma...)
The rest of them follow from this pattern.
-Travis
More information about the Numpy-discussion
mailing list