0

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.