[Numpy-discussion] index the last several members of a ndarray

Scott Sinclair scott.sinclair.za@gmail....
Tue Oct 18 08:58:27 CDT 2011


On 18 October 2011 13:56, Chao YUE <chaoyuejoy@gmail.com> wrote:
> but it's strange that if you use b[...,-1],
> you get:
> In [402]: b[...,-1]
> Out[402]: array([ 9, 19])
>
> if use b[...,-4:-1],
> you get:
> Out[403]:
> array([[ 6,  7,  8],
>        [16, 17, 18]])

That's because you're mixing two different indexing constructs. In the
first case, you're using direct indexing, so you get the values in b
at the index you specify.

In the second example you're using slicing syntax, where you get the
values in b at the range of indices starting with -4 and ending *one
before* -1 i.e. the values at b[..., -2].

Here's a simpler example:

In [1]: a = range(5)

In [2]: a
Out[2]: [0, 1, 2, 3, 4]

In [3]: a[0]
Out[3]: 0

In [4]: a[2]
Out[4]: 2

In [5]: a[0:2]
Out[5]: [0, 1]

In [6]: a[-3]
Out[6]: 2

In [7]: a[-1]
Out[7]: 4

In [8]: a[-3:-1]
Out[8]: [2, 3]

Cheers,
Scott


More information about the NumPy-Discussion mailing list