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
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.]]
However, np.reshape
gives me the following
[[ 2. 3. 4. 1. 1. 1.]
[ 1. 1. 1. 1. 1. 1.]]
How can I solve this?
Use transpose
alongwith reshape
-
a.transpose([0,2,1]).reshape(a.shape[0],-1)
Or use swapaxes
that does the same job as transpose
alongwith reshape
-
a.swapaxes(2,1).reshape(a.shape[0],-1)
Sample run -
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.]])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.