Consecutive, Overlapping Subsets of Array (NumPy, Python)

后端 未结 7 1489
北恋
北恋 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条回答
  •  Happy的楠姐
    2020-12-05 12:03

    I know of no Python stdlib function that quite does that. It's easy enough to do. Here is a generator that basically does it:

    def chunks(sequence, length):
        for index in xrange(0, len(sequence) - length + 1):
            yield sequence[index:index + length]
    

    You could use it like so

    >>> import numpy
    >>> a = numpy.arange(1, 15)
    >>> a
    array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])
    >>> numpy.array(list(chunks(a, 4)))
    array([[ 1,  2,  3,  4],
           [ 2,  3,  4,  5],
           [ 3,  4,  5,  6],
           [ 4,  5,  6,  7],
           [ 5,  6,  7,  8],
           [ 6,  7,  8,  9],
           [ 7,  8,  9, 10],
           [ 8,  9, 10, 11],
           [ 9, 10, 11, 12],
           [10, 11, 12, 13],
           [11, 12, 13, 14]])
    

    The only weird thing about this code is that I called list on the result of chunks(a, 4). This is since numpy.array does not accept an arbitrary iterable, such as the generator chunks returns. If you just want to iterate over these chunks, you don't need to bother. If you really need to put the result into an array you can do it this way or some more efficient ways.

提交回复
热议问题