I have a 1-D numpy array a = [1,2,3,4,5,6]
and a function that gets two inputs, starting_index
and ending_index
, and returns a[staring_index:ending_index]
.
Clearly I run into trouble when ending_index
is smaller than starting_index
. In this case, the function should start from the starting_index and traverse the vector a
in a circular way, i.e., return all the elements coming after starting_index
plus all the elements from index zero to ending_index
.
For instance, if starting_index=4
and ending_index=1
then the output should be output = [5,6,1]
. I can implement it with an if
condition but I was wondering if there is any Pythonic and concise way to do it?
Unfortunatly you cannot do this with slicing, you'll need to concatonate to two segments:
An alternative that you can use is the numpy
roll
function combined with indexing:This circles forever.
np.take
has awrap
mode:That's not quite what you want.
Actually, modulus does the same thing
But how about a small function that turns
(4,1)
into[4, 5, 6]
, or if you prefer[4, 5, 0]
?