Reputation: 5742
I have a before_arr
(2 x 3 x 4) multidimensional array. I want to turn it into a new_arr
(3 x 2 x 4) with a specific arrangement pattern which I wrote below.
import numpy as np
before_arr = np.array([
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
],
[
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
],
], dtype=float)
# what I want
new_arr = np.array([
[
[0, 0, 0, 0],
[1, 1, 1, 1],
],
[
[0, 0, 0, 0],
[1, 1, 1, 1],
],
[
[0, 0, 0, 0],
[1, 1, 1, 1],
],
], dtype=float)
before_arr.reshape(3, 2, 4)
doesn't give me what I want.
In [74]: before_arr.reshape(3, 2, 4)
Out[74]:
array([[[0., 0., 0., 0.],
[0., 0., 0., 0.]],
[[0., 0., 0., 0.],
[1., 1., 1., 1.]],
[[1., 1., 1., 1.],
[1., 1., 1., 1.]]])
Upvotes: 2
Views: 44
Reputation: 51165
Since you only need to swap the position of two axes, you can use np.swapaxes
. This is probably the most straightforward approach to get your desired output.
before_arr.swapaxes(0, 1)
array([[[0., 0., 0., 0.],
[1., 1., 1., 1.]],
[[0., 0., 0., 0.],
[1., 1., 1., 1.]],
[[0., 0., 0., 0.],
[1., 1., 1., 1.]]])
In a more general sense, you can use transpose
to explicitly define an ordering of axes for your desired output, which would be beneficial if you needed to move more than one axis (although not strictly required here).
before_arr.transpose(1, 0, 2)
Upvotes: 1
Reputation: 13403
use zip
to match respective rows.
try this:
import numpy as np
before_arr = np.array([
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
],
[
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
],
], dtype=float)
new_arr = np.array([*zip(*before_arr)])
print(new_arr)
Output:
[[[0. 0. 0. 0.]
[1. 1. 1. 1.]]
[[0. 0. 0. 0.]
[1. 1. 1. 1.]]
[[0. 0. 0. 0.]
[1. 1. 1. 1.]]]
Upvotes: 2