使用 numpy 构造一个数组,其中从另一个 2D 数组中提取行作为 2x2 块
假设我有以下2D数组:
x = np.array([[10,20,30,40], [50,60,70,80],[90,100,110,120]])
print(x)
array([[ 10, 20, 30, 40],
[ 50, 60, 70, 80],
[ 90, 100, 110, 120]])
我想构造一个新数组, y
,其中每一行的值来自 x
以顺时针顺序:
print(y)
array([[ 10, 20, 60, 50],
[ 20, 30, 70, 60],
[ 30, 40, 80, 70],
[ 50, 60, 100, 90],
[ 60, 70, 110, 100],
[ 70, 80, 120, 110]])
i可以使用python进行循环,如下所示:
n_rows, n_cols = x.shape
y = []
for i in range(n_rows-1):
for j in range(n_cols-1):
row = [x[i,j],x[i,j+1],x[i+1, j+1],x[i+1,j]]
y.append(row)
y = np.array(y)
我想知道是否有一种更快的方法可以利用Numpy函数并避免使用Python循环。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,创建一个进入
x
,带有您要查看的2x2框:最内在的2x2数组中的每个数组都包含您想要的内容的拆开版本,但是随着数组的第二部分逆转。到目前为止,我们还没有复制任何数据。现在,通过将最后一个维度删除来复制。重塑将始终在此处制作副本,因为
b
是高度连接的:交换最后两列:
现在ravel ravel the Leading Dimensions:
如果您有一个numpy的版本,那是较旧的whan 1.20,则可以用
b
的定义用First, create a
sliding_window_view
intox
with the 2x2 boxes you want to see:Each of the innermost 2x2 arrays contains an unraveled version of what you want, but with the second part of the array reversed. So far we didn't copy any data. Now make a copy by raveling the last dimension. The reshape will always make a copy here because
b
is highly non-contiguous:Swap the last two columns:
Now ravel the leading dimensions:
If you have a version of numpy that is older whan 1.20, you can replace the definition of
b
with您可以缓存您的代码,因为循环主要是一次又一次地迭代相同的矩阵(如果您想通过循环保留相同的代码)。我对你的代码在缓存之前和之后进行了速度比较。
现在,通过
额外的
缓存,我使用
range
添加了带有 (1000,5000) 数组的模拟数据,以显示缓存的效率。You can cache your code since the loop is mainly iterating the same matrice again and again (If you want to keep your same code with loop). I have made a speed comparison for your code before and after caching.
And now with caching
Extra
I have added simulated data with a (1000,5000) array using
range
to show the efficiency of caching.