Assuming I have a numpy array such as
[0, 1, 2, 3, 4, 5]
How do I create a 2D matrix from each 3 elements, like so:
[
[0,1,2],
[1,2,3],
[2,3,4],
[3,4,5]
]
Is there a more efficient way than using a for
loop?
Thanks.
CodePudding user response:
Yes, you can use a sliding window view:
import numpy as np
arr = np.arange(6)
view = np.lib.stride_tricks.sliding_window_view(arr, 3)
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
Keep in mind however that this is a view of the original array, not a new array.
CodePudding user response:
Since OP does not want to use a for loop we can use libraries:
You can use more-itertools
library:
#pip install more-itertools # note there is a hyphen not an underscore in installation.
l=[0, 1, 2, 3, 4, 5]
import more_itertools
list(more_itertools.windowed(l,n=3, step=1))
#output
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
or for lists of lists
list(map(list,more_itertools.windowed(l,n=3, step=1)))
[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5]]
Can also do with :
#pip install cytoolz
from cytoolz import sliding_window
list(sliding_window(3, l))
#[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]