What is the default j in (i: j: k) numpy slicing?

I read a tutorial on numpy i: j: k slicing at Scipy.org . After the second example, he says

Suppose n is the number of elements in a sliced ​​dimension. Then, if I am not specified, the default value is 0 for k> 0 and n is 1 for k <0. If j is not specified, the default value is n for k> 0 and -1 for k <0 . If k is not specified, it defaults to 1.

But:

>>> import numpy as np >>> x = np.array([0,1,2,3,4]) >>> x[::-1] array([4, 3, 2, 1, 0]) 

If j is -1 by default, then x[:-1:-1] should be equivalent to x[::-1] , but

 >>> x[:-1:-1] array([], dtype=int64) >>> x[:-(len(x)+1):-1] array([4, 3, 2, 1, 0]) 

a

 >>> x[:-(len(x)+1):-1] array([4, 3, 2, 1, 0]) 

So the default value j when k <0 should be - (n + 1). And, according to https://stackoverflow.com/a/166163/ ... , I believe that the “official” default value is j, when k <0 is None .

Am I misinterpreting a tutorial on SciPy.org?

+6
source share
1 answer

At the first level of processing, the Python interpreter converts the :: notation to a slice object. In order to interpret these 3 numbers, the numpy.__getitem__ method is used.

[::-1] same as slice(None,None,-1) .

As you note, x[slice(None,None,-1)] does not match x[slice(None,-1,-1)] .

I suspect -1 in:

If j is not given it defaults to n for k > 0 and -1 for k < 0 .

not supposed that way. Rather, it has the usual meaning of -1, the number before 0 .

In [285]: np.arange (10) [slice (5,0, -1)] Out [285]: array ([5, 4, 3, 2, 1])

j interpreted as iterate upto, but not including, this value , and the iteration direction is determined by k . Therefore, the value 0 not included in this fragment.

So how do you turn on 0 ?

 In [287]: np.arange(10)[slice(5,-1,-1)] Out[287]: array([], dtype=int32) 

does not work, as -1 means n-1 , as in:

 In [289]: np.arange(10)[slice(5,-7,-1)] Out[289]: array([5, 4]) 

None interpreted in a special way, which allows us to use:

 In [286]: np.arange(10)[slice(5,None,-1)] Out[286]: array([5, 4, 3, 2, 1, 0]) 

This also works ( 10-11=-1 - real -1 )

 In [291]: np.arange(10)[slice(5,-11,-1)] Out[291]: array([5, 4, 3, 2, 1, 0]) 

So, there is a difference between -1 , which means before 0 , and -1 , which means count from n . The documentation may be clear, but it is not (if you use the right -1).

+4
source

Source: https://habr.com/ru/post/990037/


All Articles