本文介绍了将3D矩阵转换为级联2D矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在python中有一个3D
矩阵,如下所示:
I have a 3D
matrix in python as the following:
import numpy as np
a = np.ones((2,2,3))
a[0,0,0] = 2
a[0,0,1] = 3
a[0,0,2] = 4
我想将此3D
矩阵转换为一组2D
矩阵.我已经尝试过np.reshape
,但是它不能解决我的问题.我感兴趣的最终形状是以下级联的容器:
I want to convert this 3D
matrix to a set of 2D
matrices. I have tried np.reshape
but it did not solve my problem. The final shape I am interested in is the following cascaded vesrsion:
[[ 2. 1. 3. 1. 4. 1.]
[ 1. 1. 1. 1. 1. 1.]]
但是,np.reshape
给了我以下内容
[[ 2. 3. 4. 1. 1. 1.]
[ 1. 1. 1. 1. 1. 1.]]
我该如何解决?
推荐答案
a.transpose([0,2,1]).reshape(a.shape[0],-1)
或使用 swapaxes
与transpose
和reshape
-
a.swapaxes(2,1).reshape(a.shape[0],-1)
样品运行-
In [66]: a
Out[66]:
array([[[ 2., 3., 4.],
[ 1., 1., 1.]],
[[ 1., 1., 1.],
[ 1., 1., 1.]]])
In [67]: a.transpose([0,2,1]).reshape(a.shape[0],-1)
Out[67]:
array([[ 2., 1., 3., 1., 4., 1.],
[ 1., 1., 1., 1., 1., 1.]])
In [68]: a.swapaxes(2,1).reshape(a.shape[0],-1)
Out[68]:
array([[ 2., 1., 3., 1., 4., 1.],
[ 1., 1., 1., 1., 1., 1.]])
这篇关于将3D矩阵转换为级联2D矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!