重新排列numpy数组中的元素以在2d中绘制3d数组,并保留分组

枪口

您好,我有一个3d的numpy形状数组(nc,nx,ny)。我想用x和y作为轴(用matpoltlib)绘制它,但是这样的方式是所有c值都彼此靠近,并围绕中心值排列成矩形(可以假设nc是n的幂。 2)。

感谢@ mad-physicist的回答,我认为我设法提出了一个通用的解决方案,但是它不是很有效。

我的代码如下所示:

nc1 , nc2 = 4, 4
(nx, ny, nc) = (2,3,nc1*nc2)
data = np.reshape(np.arange(nx* ny* nc),(nc, nx, ny))

res = np.zeros((nx*nc1,ny*nc2))

for i in range(nx) :
    for j in range(ny) :
        tmp = data[:,i,j].reshape(nc1,nc2)
        res[i*nc1:(i+1)*nc1,j*nc2:(j+1)*nc2] = tmp

我试图找到一种方法来避免使用numpy函数的循环。关于如何做到这一点的任何建议?

为了澄清,这是我的想法的图片。

矩阵变换

疯狂物理学家

Numpy assumes C order. So when you reshape, if your array is not C contiguous, it generally makes a copy. It also means that you can rearrange the memory layout of an array by say transposing and then reshaping it.

You want to take an array of shape (nc1 * nc2, nx, ny) into one of shape (nx * nc1, ny * nc2). One approach is to split the array into 4D first. Adding an extra dimension will not change the memory layout:

data = data.reshape(nc1, nc2, nx, ny)

Now you can move the dimensions around to get the memory layout you need. This will change your strides without copying memory, since the array is still C contiguous in the last step:

data = data.transpose(2, 0, 3, 1) # nx, nc1, ny, nc2

请注意,我们感动nc1之后nxnc2之后ny在C顺序中,我们希望组是连续的。较晚的尺寸比较早的尺寸靠得很近。因此,闲逛[[1, 2], [3, 4]]产生[1, 2, 3, 4],而闲逛[[1, 3], [2, 4]]产生[1, 3, 2, 4]

现在您可以获得最终的数组。由于数据在重新排列尺寸后不再是C连续的,因此以下重新整形将使副本实际重新排列数据:

data = data.reshape(nx * nc1, ny * nc2)

您可以将其写成一行:

result = data.reshape(nc1, nc2, nx, ny).transpose(2, 0, 3, 1).reshape(nx * nc1, ny * nc2)

原则上,这是您所能达到的最高效率:第一次重塑会改变形状并大步前进;换位围绕形状的顺序交换并大步移动。在最后一次重塑期间仅发生一次复制操作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章