circular numpy array indices

前端 未结 4 1457
既然无缘
既然无缘 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:32

    This circles forever.

    def circular_indices(lb, ub, thresh):
        indices = []
        while True:
            stop = min(ub, thresh)
            ix = np.arange(lb, stop)
            indices.append(ix)
            if stop != ub:
                diff = ub - stop
                lb = 0
                ub = diff
            else:
                break
    
        return np.concatenate(indices)
    
    0 讨论(0)
  • 2021-02-20 14:35

    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]
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2021-02-20 14:58

    An alternative that you can use is the numpy roll function combined with indexing:

    # -*- coding: utf-8 -*-
    import numpy as np
    
    def circular_array(starting_index, ending_index):
    
        idx = np.arange(1,7)
        idx = np.roll(idx, -starting_index)[:(len(idx)-starting_index+ending_index)%len(idx)]
    
        return idx
    
    
    a = circular_array(4, 1)
    print a
    
    0 讨论(0)
提交回复
热议问题