Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all except first and last n elements of a numpy array

I want to get all but the first and last n elements from an array, can I do this while keeping consistent behaviour for n=0 without using an if statement? (Python 2.7). This does what I want, but falls apart if nCut=0:

nCut = 3
newArray = oldArray[nCut:-nCut]

This is closer, but doesn't include the last element (and is also really just a slightly hidden if statement)

newArray = oldArray[nCut:-nCut-1*(nCut<1)]

I have to do this to a bunch of arrays I'm loading from files, so not having a big ugly doubled up if for the n=0 case would be nice.

like image 743
llama Avatar asked Feb 01 '18 00:02

llama


People also ask

What types of letters are allowed in a NumPy array?

Lowercase letters, numbers, and dashes are allowed. Have another way to solve this solution? Contribute your code (and comments) through Disqus. Previous: Write a NumPy program to extract first and second elements of the first and second rows from a given (4x4) array.

How to extract the first row from a 4x4 array in NumPy?

Write a NumPy program to extract all the elements of the first row from a given (4x4) array. import numpy as np arra_data = np.arange (0,16).reshape ( (4, 4)) print ("Original array:") print (arra_data) print (" Extracted data: First row") print (arra_data [0])

How to get the last index of an element in NumPy?

You can simply use take method and index of element (Last index can be -1). arr = np.array ([1,2,3]) last = arr.take (-1) # 3

How to get values of an NumPy array at certain index positions?

- GeeksforGeeks How to get values of an NumPy array at certain index positions? Sometimes we need to remove values from the source Numpy array and add them at specific indices in the target array. In NumPy, we have this flexibility, we can remove values from one array and add them to another array.


1 Answers

Add len(oldArray) yourself instead of counting on the slicing implementation to do it for you:

newArray = oldArray[nCut:len(oldArray)-nCut]

You can also use -nCut or None to use None as the endpoint if it would otherwise be 0:

newArray = oldArray[nCut:-nCut or None]

None is what a slice endpoint is set to if you don't write one in, so this is equivalent to oldArray[nCut:] when nCut is 0. This is less immediately understandable, but also less verbose. It may be a better choice in cases of multidimensional slicing, or if the expression for the array is more complex than just oldArray.

like image 192
user2357112 supports Monica Avatar answered Oct 02 '22 08:10

user2357112 supports Monica