Numpy rolling window over 2D array, as a 1D array with nested array as data values
<p>When using <code>np.lib.stride_tricks.as_strided</code>, how can I manage 2D a array with the nested arrays as data values? Is there a preferable <strong>efficient</strong> approach?</p>

<p>Specifically, if I have a 2D <code>np.array</code> looking as follows, where each data item in a 1D array is an array of length 2:</p>

<pre><code>[[1., 2.],[3., 4.],[5.,6.],[7.,8.],[9.,10.]...]
</code></pre>

<p>I want to reshape for rolling over as follows:</p>

<pre><code>[[[1., 2.],[3., 4.],[5.,6.]],
 [[3., 4.],[5.,6.],[7.,8.]],
 [[5.,6.],[7.,8.],[9.,10.]],
  ...
]
</code></pre>

<p>I have had a look at similar answers (e.g. <a href="http://stackoverflow.com/a/6811241/6334309">this rolling window function</a>), however in use I cannot leave the inner array/tuples untouched.</p>

<p>For example with a window length of <code>3</code>: I have tried a <code>shape</code> of <code>(len(seq)+3-1, 3, 2)</code> and a <code>stride</code> of <code>(2 * 8, 2 * 8, 8)</code>, but no luck. Maybe I am missing something obvious?</p>

<p>Cheers.</p>

<hr>

<p><strong>EDIT:</strong> It is easy to produce a functionally identical solution using Python built-ins (which can be optimised using e.g. <code>np.arange</code> similar to Divakar's solution), however, what about using <code>as_strided</code>? From my understanding, this could be used for a highly efficient solution?</p>

<p>IIUC you could do something like this -</p>

<pre><code>def rolling_window2D(a,n):
    # a: 2D Input array 
    # n: Group/sliding window length
    return a[np.arange(a.shape[0]-n+1)[:,None] + np.arange(n)]
</code></pre>

<p>Sample run -</p>

<pre><code>In [110]: a
Out[110]: 
array([[ 1,  2],
       [ 3,  4],
       [ 5,  6],
       [ 7,  8],
       [ 9, 10]])

In [111]: rolling_window2D(a,3)
Out[111]: 
array([[[ 1,  2],
        [ 3,  4],
        [ 5,  6]],

       [[ 3,  4],
        [ 5,  6],
        [ 7,  8]],

       [[ 5,  6],
        [ 7,  8],
        [ 9, 10]]])
</code></pre>

python arrays performance numpy sliding-window