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?
You task is similar to this one. So I slightly changed it.
What was wrong with your
as_strided
trial? It works for me.On my first edit I used an
int
array, so had to use(8,8,4)
for the strides.Your shape could be wrong. If too large it starts seeing values off the end of the data buffer.
Here it just alters the display method, the
7, 8, 9, 10
are still there. Writing those those slots could be dangerous, messing up other parts of your code.as_strided
is best if used for read-only purposes. Writes/sets are trickier.IIUC you could do something like this -
Sample run -