繁体   English   中英

从一维数组创建二维数组 - Python Numpy

[英]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.

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