Consecutive, Overlapping Subsets of Array (NumPy, Python)

后端 未结 7 1452
北恋
北恋 2020-12-05 11:52

I have a NumPy array [1,2,3,4,5,6,7,8,9,10,11,12,13,14] and want to have an array structured like [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]

相关标签:
7条回答
  • 2020-12-05 12:15

    Broadcast!

    from numpy import ogrid
    def stretch(N=5,M=15):
        x, y = ogrid[0:M,0:N]
        return x+y+1
    

    Note that ogrid does give things like:

    >> ogrid[0:5,0:5]
    >> 
    [array([[0],
           [1],
           [2],
           [3],
           [4]]),
     array([[0, 1, 2, 3, 4]])]
    

    Let's compare with another solution given here:

    def zipping(N=5,M=15):
        A = numpy.arange(1, M+1)
        return numpy.array(zip(*(A[i:] for i in range(N))))
    

    comparison (python 2.6, 32 bit, 1Go RAM) gives

    >>> %timeit stretch(5,15)
    10000 loops, best of 3: 61.2 us per loop
    
    >>> %timeit zipping(5,15)
    10000 loops, best of 3: 72.5 us per loop
    
    >>> %timeit stretch(5,1e3)
    10000 loops, best of 3: 128 us per loop
    
    >>> %timeit zipping(5,1e3)
    100 loops, best of 3: 4.25 ms per loop
    

    The 40-fold speed-up is kind of consistant to scaling.

    0 讨论(0)
提交回复
热议问题