Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating 2D array from 1D array – Python Numpy

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


Thanks.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading