Reputation: 8536
I have a [? 5 5] array: (?=3 in this case)
[[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
[[25 26 27 28 29]
[30 31 32 33 34]
[35 36 37 38 39]
[40 41 42 43 44]
[45 46 47 48 49]]
[[50 51 52 53 54]
[55 56 57 58 59]
[60 61 62 63 64]
[65 66 67 68 69]
[70 71 72 73 74]]]
I want to have 5 (the # of row) separate array have (? 5) like this:
[array([[ 0, 1, 2, 3, 4],
[25, 26, 27, 28, 29],
[50, 51, 52, 53, 54]]),
array([[ 5, 6, 7, 8, 9],
[30, 31, 32, 33, 34],
[55, 56, 57, 58, 59]]),
array([[10, 11, 12, 13, 14],
[35, 36, 37, 38, 39],
[60, 61, 62, 63, 64]]),
array([[15, 16, 17, 18, 19],
[40, 41, 42, 43, 44],
[65, 66, 67, 68, 69]]),
array([[20, 21, 22, 23, 24],
[45, 46, 47, 48, 49],
[70, 71, 72, 73, 74]])]
Is this a simple preferably one/two numpy operation way to do this?
Upvotes: 0
Views: 523
Reputation: 15909
Just to propose an alternative solution, np.swapaxes
is another alternative to np.transpose
when only a pair of axes is involved.
a, b, c, d, e = arr.swapaxes(0, 1) # swap axes 0, 1
swapaxes
will always return a view of the array, with the same result as the np.transpose
proposed by @roadrunner66. It is usually just sightly faster than transpose
and heavily used inside numpy
's code to put the important dimension up-front.
Upvotes: 2
Reputation: 7941
Yes, there is : numpy.transpose
. You get to chose any sequence in the axes of your 3D structure.
import numpy as np
aaa=np.array([[[ 0 , 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]],
[[25, 26, 27, 28, 29],
[30, 31, 32, 33, 34],
[35, 36, 37, 38, 39],
[40, 41, 42, 43, 44],
[45, 46, 47, 48, 49]],
[[50, 51, 52, 53, 54],
[55, 56, 57, 58, 59],
[60, 61, 62, 63, 64],
[65, 66, 67, 68, 69],
[70, 71, 72, 73, 74]]])
bb= np.transpose(aaa,axes=[1,0,2])
print bb
output:
[[[ 0 1 2 3 4]
[25 26 27 28 29]
[50 51 52 53 54]]
[[ 5 6 7 8 9]
[30 31 32 33 34]
[55 56 57 58 59]]
[[10 11 12 13 14]
[35 36 37 38 39]
[60 61 62 63 64]]
[[15 16 17 18 19]
[40 41 42 43 44]
[65 66 67 68 69]]
[[20 21 22 23 24]
[45 46 47 48 49]
[70 71 72 73 74]]].
To access the subarrays, just use indexing like so:
c= b[0]
print c
Output:
[[ 0 1 2 3 4]
[25 26 27 28 29]
[50 51 52 53 54]]
Upvotes: 2