如何将Numpy多层级矩阵转换为指定拼接结构的4×4矩阵?
问题描述
我拥有以下4个Numpy矩阵:
>>> a array([[0., 0.], [0., 0.]]) >>> b array([[1., 1.], [1., 1.]]) >>> c array([[2., 2.], [2., 2.]]) >>> d array([[3., 3.], [3., 3.]])
将它们组合为矩阵e:
>>> e = np.array([[a,b], [c,d]]) >>> e.shape (2, 2, 2, 2)
希望将e转换为如下形式的4×4矩阵:
0 0 1 1 0 0 1 1 2 2 3 3 2 2 3 3
但使用e.reshape((4,4))得到的是:
>>> e.reshape((4,4)) array([[0., 0., 0., 0.], [1., 1., 1., 1.], [2., 2., 2., 2.], [3., 3., 3., 3.]])
请问是否有方法将形状为(2,2,2,2)的矩阵e转换为目标结构的4×4矩阵?
解决方案
可以通过调整数组轴顺序后再reshape,或者直接用专用构造函数实现目标效果:
方法1:调整轴顺序后reshape
针对已构造好的e,先通过transpose调整轴的排列顺序,再执行reshape:
import numpy as np # 假设e已构造完成 result = e.transpose(0, 2, 1, 3).reshape(4, 4) print(result)
输出结果:
array([[0., 0., 1., 1.], [0., 0., 1., 1.], [2., 2., 3., 3.], [2., 2., 3., 3.]])
原理:原数组e的轴顺序是(块行, 块列, 块内行, 块内列),transpose(0,2,1,3)将轴调整为(块行, 块内行, 块列, 块内列),此时元素排列逻辑已匹配目标结构,reshape后即可得到想要的4×4矩阵。
方法2:直接用block构造目标矩阵
如果还未将a、b、c、d组合成e,可以直接用numpy.block一步构造目标矩阵,跳过后续调整步骤:
result = np.block([[a, b], [c, d]]) print(result)
输出同样符合要求的4×4矩阵。
内容的提问来源于stack exchange,提问作者SomethingSomething
相关产品推荐
相关产品推荐

