Question
How do I reshape a 2D matrix to a 3D matrix where columns are moved "depth-wise"?
I want array a to look like array b
import numpy as np
a = np.array([
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3]
])
b = np.array([
[[1,1,1,1,1,1],
[1,1,1,1,1,1],
[1,1,1,1,1,1],
[1,1,1,1,1,1]],
[[2,2,2,2,2,2],
[2,2,2,2,2,2],
[2,2,2,2,2,2],
[2,2,2,2,2,2]],
[[3,3,3,3,3,3],
[3,3,3,3,3,3],
[3,3,3,3,3,3],
[3,3,3,3,3,3]],
])
What I tried to do
The result is not the result that I want to achieve
x = np.reshape(a, (a.shape[0], -1, 3))
I've also tried the following: 1) hsplit a into 3 sets 2) tried to dstack these sets but doesn't produce wanted result
b = np.hsplit(a,3)
c = np.dstack([b[0],b[1],b[2]])
this should do:
import numpy as np
a = np.array([
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3],
[1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3]
])
b = np.array([
[[1,1,1,1,1,1],
[1,1,1,1,1,1],
[1,1,1,1,1,1],
[1,1,1,1,1,1]],
[[2,2,2,2,2,2],
[2,2,2,2,2,2],
[2,2,2,2,2,2],
[2,2,2,2,2,2]],
[[3,3,3,3,3,3],
[3,3,3,3,3,3],
[3,3,3,3,3,3],
[3,3,3,3,3,3]],
])
a_new = np.swapaxes(a.reshape(a.shape[0], 3, -1), 0, 1)
np.array_equal(a_new, b)
-> True
You just need transpose
which is T
and reshape
a.T.reshape(3,4,6)
or
a.T.reshape(b.shape)
Out[246]:
array([[[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1]],
[[2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2],
[2, 2, 2, 2, 2, 2]],
[[3, 3, 3, 3, 3, 3],
[3, 3, 3, 3, 3, 3],
[3, 3, 3, 3, 3, 3],
[3, 3, 3, 3, 3, 3]]])
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.