[编辑-我假设小数组是独立创建的,尽管我的示例基于拆分 (4,2,2) 数组。如果它们真的只是 3d 数组的平面,那么“reshape”和“transpose”的某种组合会更好。但即使是这样的解决方案也会产生一个副本,因为原始值被重新排列。]
让我们列出一个 2x2 数组(这里是 3d 数组)。需要挤压,因为这种拆分会产生 (1,2,2) 数组:
n = len(A)
E = np.zeros((n,n))
In [330]: X=np.arange(1,17).reshape(4,2,2)
In [331]: xl=[np.squeeze(i) for i in np.split(X,4,0)]
In [332]: xl
Out[332]:
[array([[1, 2],
[3, 4]]), array([[5, 6],
[7, 8]]), array([[ 9, 10],
[11, 12]]), array([[13, 14],
[15, 16]])]
您的 bmat 方法 - 已更正以生成方形排列
In [333]: np.bmat([[xl[0],xl[1]],[xl[2],xl[3]]])
Out[333]:
matrix([[ 1, 2, 5, 6],
[ 3, 4, 7, 8],
[ 9, 10, 13, 14],
[11, 12, 15, 16]])
一种连接方法:
In [334]: np.vstack([np.hstack(xl[:2]),np.hstack(xl[2:])])
Out[334]:
array([[ 1, 2, 5, 6],
[ 3, 4, 7, 8],
[ 9, 10, 13, 14],
[11, 12, 15, 16]])
由于切片在hstack 中有效,我也可以在bmat 中使用它:
In [335]: np.bmat([xl[:2],xl[2:]])
Out[335]:
matrix([[ 1, 2, 5, 6],
[ 3, 4, 7, 8],
[ 9, 10, 13, 14],
[11, 12, 15, 16]])
在内部bmat(检查其代码)正在使用vstack 的版本hstacks(在第一个和最后一个轴上接触)。有效
In [366]: ll=[xl[:2], xl[2:]]
In [367]: np.vstack([np.hstack(row) for row in ll])
Out[367]:
array([[ 1, 2, 5, 6],
[ 3, 4, 7, 8],
[ 9, 10, 13, 14],
[11, 12, 15, 16]])
您必须如何指定这些n 数组的排列方式。 np.bmat(xl) 产生一个(2,8) 矩阵(hstack 也是如此)。 np.vstack(xl) 产生一个 (8,2) 数组。
扩展它以使用 3x3、2x3 等子阵列布局应该不难。 xl 是一个子数组列表。将其重新加工成所需的子数组列表并应用bmat 或stacks 的组合。
2x3 布局的 2 个快速版本(4d xl 数组比 2x3 嵌套列表更容易构建,但功能相同:
In [369]: xl=np.arange(3*2*2*2).reshape((3,2,2,2))
In [370]: np.vstack([np.hstack(row) for row in xl])
Out[370]:
array([[ 0, 1, 4, 5],
[ 2, 3, 6, 7],
[ 8, 9, 12, 13],
[10, 11, 14, 15],
[16, 17, 20, 21],
[18, 19, 22, 23]])
In [371]: xl=np.arange(2*3*2*2).reshape((2,3,2,2))
In [372]: np.vstack([np.hstack(row) for row in xl])
Out[372]:
array([[ 0, 1, 4, 5, 8, 9],
[ 2, 3, 6, 7, 10, 11],
[12, 13, 16, 17, 20, 21],
[14, 15, 18, 19, 22, 23]])