Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy negative indexing a[:-0]

Tags:

I want to use array slicing to trim my array i.e.

a_trimmed = a[trim_left:-trim_right] 

this is great, except if trim_right is 0, I get a[trim_left:0], which is an empty array.

I suppose I can could it to

a[trim_left:a.shape[0]-trim_right] 

but it's uglier. What's the cleanest way to express this?

like image 618
so12311 Avatar asked Feb 20 '14 16:02

so12311


People also ask

What is negative indexing in NumPy array?

Negative indices are interpreted as counting from the end of the array (i.e., if i < 0, it means n_i + i). All arrays generated by basic slicing are always views of the original array. The standard rules of sequence slicing apply to basic slicing on a per-dimension basis (including using a step index).

Is NumPy 0 indexed?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do you make a Python index negative?

To recap, Python supports positive zero-based indexing and negative indexing that starts from -1. Negative indexing in Python means the indexing starts from the end of the iterable. The last element is at index -1, the second last at -2, and so on.

How do you do negative indexing?

This means that the index value of -1 gives the last element, and -2 gives the second last element of an array. The negative indexing starts from where the array ends. This means that the last element of the array is the first element in the negative indexing which is -1.


1 Answers

None is a valid slice endpoint:

a[trim_left:-trim_right or None] 
like image 183
lanzz Avatar answered Sep 21 '22 13:09

lanzz