且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Numpy 3D数组转换为2D数组

更新时间:2023-08-28 16:54:34

您需要进行一次6D重塑,基本上将每个轴分成两个,然后转置为推回偶数轴(第2,第4和第6)),最后重新塑形为2D-

You need to go 6D with one reshaping basically splitting each axes into two, then transpose to push back the even axes (2nd, 4th and 6th) to the end and a final reshape back to 2D -

a.reshape(-1,3,3,3,3,3).transpose(0,2,4,1,3,5).reshape(27,27)

样品运行-

In [28]: a = np.arange(729).reshape((9,9,9))

In [29]: out = a.reshape(-1,3,3,3,3,3).transpose(0,2,4,1,3,5).reshape(27,27)

In [30]: out[0]
Out[30]: 
array([  0,   1,   2,   9,  10,  11,  18,  19,  20,  81,  82,  83,  90,
        91,  92,  99, 100, 101, 162, 163, 164, 171, 172, 173, 180, 181, 182])

In [31]: out[1]
Out[31]: 
array([  3,   4,   5,  12,  13,  14,  21,  22,  23,  84,  85,  86,  93,
        94,  95, 102, 103, 104, 165, 166, 167, 174, 175, 176, 183, 184, 185])

In [32]: out[2]
Out[32]: 
array([  6,   7,   8,  15,  16,  17,  24,  25,  26,  87,  88,  89,  96,
        97,  98, 105, 106, 107, 168, 169, 170, 177, 178, 179, 186, 187, 188])

In [33]: out[3]
Out[33]: 
array([ 27,  28,  29,  36,  37,  38,  45,  46,  47, 108, 109, 110, 117,
       118, 119, 126, 127, 128, 189, 190, 191, 198, 199, 200, 207, 208, 209])

In [34]: out[-1]
Out[34]: 
array([546, 547, 548, 555, 556, 557, 564, 565, 566, 627, 628, 629, 636,
       637, 638, 645, 646, 647, 708, 709, 710, 717, 718, 719, 726, 727, 728])

通用案例解决方案

BSZ = [3,3] # Block size
p,q = BSZ
out = a.reshape(p,q,p,q,p,q).transpose(0,2,4,1,3,5).reshape(p**3,q**3)