在Numpy中高效地构建“滚动"行矩阵 [英] Building a matrix of 'rolled' rows efficiently in Numpy
本文介绍了在Numpy中高效地构建“滚动"行矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从一维数组构造一个(n,n)
数组,其中每行相对于上一行移动(带换行).下面的代码可以做到这一点:
I'd like to construct a (n,n)
-array from a one dimensional array, where each row is shifted (with wrapping) by one relative to the previous one. The following code does this:
import numpy as np
r = np.array([1, 2, 3, 4, 5])
n = len(r)
MM = np.zeros((n, n), dtype=r.dtype)
for k in range(n):
MM[k, :] = np.roll(r, k)
print(MM)
其结果是:
[[1 2 3 4 5]
[5 1 2 3 4]
[4 5 1 2 3]
[3 4 5 1 2]
[2 3 4 5 1]]
对于Numpy中的大型r
,是否有一种方法可以更快地执行Numpy,即避免for
循环?
Is there a way to do this Numpy faster, i.e., avoiding the for
-loop, for large r
in Numpy?
推荐答案
In [257]: toeplitz(np.roll(r[::-1], 1), r)
Out[257]:
array([[1, 2, 3, 4, 5],
[5, 1, 2, 3, 4],
[4, 5, 1, 2, 3],
[3, 4, 5, 1, 2],
[2, 3, 4, 5, 1]])
这篇关于在Numpy中高效地构建“滚动"行矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文