I have an array like
[1,3,4,5,6,2,1,,,,]
now, I want to change it to
[[1,3,4],[3,4,5],[4,5,6],[5,6,2],,,,]
How can I achieve this using numpy? Is there any function to do so? And, using loop is not an option.
I have an array like
[1,3,4,5,6,2,1,,,,]
now, I want to change it to
[[1,3,4],[3,4,5],[4,5,6],[5,6,2],,,,]
How can I achieve this using numpy? Is there any function to do so? And, using loop is not an option.
np.lib.stride_tricks.as_strided method will does that.
Here strides is (4,4) for 32 bit int. If you want more flexible code, I have commented stride parameter in the code. shape parameter determines output array dimensions.
> import numpy as np
> A = [1,2,3,4,5,6]
> n = 3 # output matrix has 3 columns
> m = len(A) - (n-1) # calculate number of output matrix rows using input matrix length
> # strides_param = np.array(A, dtype=np.int32).strides * 2
> np.lib.stride_tricks.as_strided(A, shape=(m,n), strides=(4,4))
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6]])
Using list comprehension instead of a library but why make it complicated. (Do you consider this a loop?)
x = [1,3,4,5,6,2,1]
y = [x[n:n+3] for n in range(len(x)-2)]
Result is:
[[1, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 2], [6, 2, 1]]