27

Suppose we have the following array:

import numpy as np
a = np.arange(1, 10)
a = a.reshape(len(a), 1)
array([[1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7],
       [8],
       [9]])

Now, i want to access the elements from index 4 to the end:

a[3:-1]
array([[4],
       [5],
       [6],
       [7],
       [8]])
 

When i do this, the resulting vector is missing the last element, now there are five elements instead of six, why does it happen, and how can i get the last element without appending it?

Expected output:

array([[4],
       [5],
       [6],
       [7],
       [8],
       [9]])
starball
  • 20,030
  • 7
  • 43
  • 238

1 Answers1

68

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Understanding slicing

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • That worked indeed, thanks, i'm trying to convert some matlab code to python/numpy, and that reference guide [NumPy fot Matlab users](http://www.scipy.org/NumPy_for_Matlab_Users) misses some important issues as indexing and slicing. – Edgar Andrés Margffoy Tuay Dec 05 '12 at 20:51
  • @Andfoy: I'd recommend reading the NumPy tutorial I linked to. It's not perfect, but should be a good start. – NPE Dec 05 '12 at 20:55
  • 2
    Is there an object or other "index" that can go where the -1 is to make it behave like `a[3:]`? I often find it would simplify the code I write.. – Brian Nov 02 '15 at 22:23
  • 20
    I found the answer--use `None`--like `a[3:None]`. – Brian Nov 02 '15 at 22:30