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?
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).
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.
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.
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.
None
is a valid slice endpoint:
a[trim_left:-trim_right or None]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With