circular numpy array indices

前端 未结 4 1454
既然无缘
既然无缘 2021-02-20 14:04

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[stari

4条回答
  •  执笔经年
    2021-02-20 14:40

    np.take has a wrap mode:

    In [171]: np.take(np.arange(1,7),range(4,7),mode='wrap')
    Out[171]: array([5, 6, 1])
    

    That's not quite what you want.

    Actually, modulus does the same thing

    In [177]: a[np.array([4,5,6])%6]
    Out[177]: array([5, 6, 1])
    

    But how about a small function that turns (4,1) into [4, 5, 6], or if you prefer [4, 5, 0]?

    def foo(a, start, stop): 
        # fn to convert your start stop to a wrapped range
        if stop<=start:
            stop += len(a)
        return np.arange(start, stop)%len(a)
    
    a[foo(a,4,1)]  # or
    np.take(a,foo(a,4,1))
    

提交回复
热议问题