简体   繁体   中英

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?


Thanks.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM