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>What was wrong with your <code>as_strided</code> trial?  It works for me.</p>

<pre><code>In [28]: x=np.arange(1,11.).reshape(5,2)
In [29]: x.shape
Out[29]: (5, 2)
In [30]: x.strides
Out[30]: (16, 8)
In [31]: np.lib.stride_tricks.as_strided(x,shape=(3,3,2),strides=(16,16,8))
Out[31]: 
array([[[  1.,   2.],
        [  3.,   4.],
        [  5.,   6.]],

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

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

<p>On my first edit I used an <code>int</code> array, so had to use <code>(8,8,4)</code> for the strides.</p>

<p>Your shape could be wrong.  If too large it starts seeing values off the end of the data buffer.</p>

<pre><code>   [[  7.00000000e+000,   8.00000000e+000],
    [  9.00000000e+000,   1.00000000e+001],
    [  8.19968827e-257,   5.30498948e-313]]])
</code></pre>

<p>Here it just alters the display method, the <code>7, 8, 9, 10</code> are still there.    Writing those those slots could be dangerous, messing up other parts of your code.  <code>as_strided</code> is best if used for read-only purposes.  Writes/sets are trickier.</p>

python arrays performance numpy sliding-window