将4d numpy数组重塑为2d数组,同时保留数组位置 [英] Reshape 4d numpy array to 2d array while preserving array locations

查看:96
本文介绍了将4d numpy数组重塑为2d数组,同时保留数组位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形状为(N, N, Q, Q)的4维numpy数组.因此,给定行索引和列索引(i, j)mat[i,j]是一个QxQ矩阵.我想重塑此数组的形状以使(N*Q, N*Q)如此

I have a 4 dimensional numpy array of shape (N, N, Q, Q). So given a row and column index (i, j), mat[i,j] is a QxQ matrix. I want to reshape this array to shape (N*Q, N*Q) such that

array([[[[ 0,  1],
         [ 2,  3]],

        [[ 4,  5],
         [ 6,  7]]],


       [[[ 8,  9],
         [10, 11]],

        [[12, 13],
         [14, 15]]]])

转到

array([[  0.,   1.,   4.,   5.],
       [  2.,   3.,   6.,   7.],
       [  8.,   9.,  12.,  13.],
       [ 10.,  11.,  14.,  15.]])

您可以看到mat[0,0]转到new_mat[0:2, 0:2].当前mat.reshape(N*Q, N*Q)mat[0,0]带到new_mat[0:4, 0](这是我不想要的).如何使用重塑或横轴或类似方法重塑此数组?我最终想用imshow绘制它,目前卡住了.我认为这很容易做到,但我还没有弄清楚.

You can see that mat[0,0] goes to new_mat[0:2, 0:2]. Currently mat.reshape(N*Q, N*Q) takes mat[0,0] to new_mat[0:4, 0] (which is what I do not want). How can I use reshape or rollaxis or something similar to reshape this array? I eventually want to plot it with imshow, am currently stuck. I figure it's easy to do, I just haven't yet figured it out.

推荐答案

没关系,我知道了. np.swapaxes(1, 2)是我需要的失物.

Nevermind, I figured it out. np.swapaxes(1, 2) was the missing piece I needed.

答案只是要做mat.swapaxes(1, 2).reshape(N*Q, N*Q).

对于发布而感到愚蠢,而又不想自己弄太久,但我将其保留,以便其他人可以从中受益.

Feel foolish for posting without attempting to figure it out myself for too long, but I'll leave it up so others can benefit from it.

这篇关于将4d numpy数组重塑为2d数组,同时保留数组位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆