Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array elements from index to end

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

Thanks in advance

like image 908
Edgar Andrés Margffoy Tuay Avatar asked Dec 05 '12 20:12

Edgar Andrés Margffoy Tuay


People also ask

How do I get the last index of an array?

lastIndexOf() The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex .

Can you use indexOf on an array?

Introduction to the JavaScript array indexOf() methodTo find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

How do I find the last 5 elements of an array?

To get the last N elements of an array, call the slice method on the array, passing in -n as a parameter, e.g. arr. slice(-3) returns a new array containing the last 3 elements of the original array. Copied! const arr = ['a', 'b', 'c', 'd', 'e']; const last3 = arr.

How do you access part of an array in Python?

Overview. An array in Python is used to store multiple values or items or elements of the same type in a single variable. We can access elements of an array using the index operator [] .


1 Answers

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

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

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

like image 99
NPE Avatar answered Oct 19 '22 05:10

NPE