Inverted array in numpy?

A sample tutorial on a bum suggests that a[ : :-1] is the opposite of a . Can someone explain to me how we got there?

I understand that a[:] means for each element a (with axis = 0). Next : should indicate the number of elements to be skipped (or period) from my understanding.

+6
source share
3 answers

As others have noted, this is a python slicing method, and numpy just follows suit. Hope this helps explain how this works:

The last bit is a step. 1 indicates a step one element at a time - does this in reverse order.

Forms indicate the first and last, if you do not have a negative step, in which case they indicate the last and first:

 In [1]: import numpy as np In [2]: a = np.arange(5) In [3]: a Out[3]: array([0, 1, 2, 3, 4]) In [4]: a[0:5:1] Out[4]: array([0, 1, 2, 3, 4]) In [5]: a[0:5:-1] Out[5]: array([], dtype=int64) In [6]: a[5:0:-1] Out[6]: array([4, 3, 2, 1]) In [7]: a[::-2] Out[7]: array([4, 2, 0]) 

Line 5 gives an empty array as it tries to step back from element 0 th to 5 th.
The slice does not include the "end point" (called the last element), so line 6 skips 0 when moving backward.

+4
source

This is not numpy, this is Python.

Python has snippets for sequence / iterable that go into the following syntax

 seq[start:stop:step] => a slice from start to stop, stepping step each time. 

All arguments are optional, but Python must be present for this : to recognize this as a slice.

Negative values ​​for the step also work to make a copy of the same sequence / iterable in reverse order:

 >>> L = range(10) >>> L[::-1] [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 

And numpy follows that β€œrule”, like any good third-party library.

 >>> a = numpy.array(range(10)) >>> a[::-1] array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) 

See this link

+10
source

This does not apply to numpy, slice a[::-1] equivalent to slice(None, None, -1) , where the first argument is the start index, the second argument is the end index, and the third argument is the step. None to start or stop will have the same behavior as using the beginning or end of a sequence, and -1 for a step will iterate over the sequence in reverse order.

+3
source

All Articles