Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

circular numpy array indices

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?

like image 333
TNM Avatar asked Feb 08 '15 19:02

TNM


1 Answers

Unfortunatly you cannot do this with slicing, you'll need to concatonate to two segments:

import numpy as np

a = [1, 2, 3, 4, 5, 6]
if starting_index > ending_index:
    part1 = a[start_index:]
    part2 = a[:end_index]
    result = np.concatenate([part1, part2])
else:
    result = a[start_index:end_index]
like image 135
Bi Rico Avatar answered Sep 19 '22 13:09

Bi Rico