When using np.lib.stride_tricks.as_strided
, how can I manage 2D a array with the nested arrays as data values? Is there a preferable efficient approach?
Specifically, if I have a 2D np.array
looking as follows, where each data item in a 1D array is an array of length 2:
[[1., 2.],[3., 4.],[5.,6.],[7.,8.],[9.,10.]...]
I want to reshape for rolling over as follows:
[[[1., 2.],[3., 4.],[5.,6.]],
[[3., 4.],[5.,6.],[7.,8.]],
[[5.,6.],[7.,8.],[9.,10.]],
...
]
I have had a look at similar answers (e.g. this rolling window function), however in use I cannot leave the inner array/tuples untouched.
For example with a window length of 3
: I have tried a shape
of (len(seq)+3-1, 3, 2)
and a stride
of (2 * 8, 2 * 8, 8)
, but no luck. Maybe I am missing something obvious?
Cheers.
EDIT: It is easy to produce a functionally identical solution using Python built-ins (which can be optimised using e.g. np.arange
similar to Divakar's solution), however, what about using as_strided
? From my understanding, this could be used for a highly efficient solution?