Get array elements from index to end

Question:

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]])

Answers:

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.

Answered By: NPE
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.