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]].
Sure this is possible by looping over the large array and adding arrays of length four to the new array, but I’m curious if there is some secret ‘magic’ Python method doing just this 🙂
The fastest way seems to be to preallocate the array, given as option 7 right at the bottom of this answer.
You can easily adapt this to do it for variable chunk size.
You may wish to compare performance between this and using
itertools.islice.My timing results:
As len(A) increases (20000) 4 and 5 converge to be equivalent speed (44 ms). 1,2,3 and 6 all remain about 3 times slower (135 ms). 7 is much faster (1.36 ms).