[英]Creating 2D array from 1D array - Python Numpy
假設我有一個 numpy 數組,例如
[0, 1, 2, 3, 4, 5]
如何從每 3 個元素創建一個 2D 矩陣,如下所示:
[
[0,1,2],
[1,2,3],
[2,3,4],
[3,4,5]
]
有沒有比使用for
循環更有效的方法?
謝謝。
是的,您可以使用滑動 window 視圖:
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]])
但是請記住,這是原始數組的視圖,而不是新數組。
由於 OP 不想使用 for 循環,我們可以使用庫:
您可以使用more-itertools
庫:
#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)]
或列表列表
list(map(list,more_itertools.windowed(l,n=3, step=1)))
[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5]]
也可以做:
#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)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.