Reputation: 198
I have a Numpy array called z:
pop = np.random.randint(4, size = (3, 3, 1, 5))
z = pop.reshape(tuple(d for d in pop.shape if d > 1))
Using the following code, I manage to print it like this:
for x in z:
for y in x:
print(y, end=' ')
print()
But now I need vertically each individual element of the array, for demonstration purposes, something like this:
Thanks for any advice.
Upvotes: 0
Views: 5631
Reputation: 231385
In [277]: pop = np.arange(9*5).reshape(3,3,1,5)
In [278]: pop
Out[278]:
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]]]])
Swap the last two axes will give the required 'column vectors':
In [279]: pop.transpose(0,1,3,2)
Out[279]:
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]]]])
Then with a word processing block move, rearrange the blocks.
Another transpose and reshape would order the values in the desired way, but the brackets would not be what you want:
In [281]: pop.transpose(0,3,2,1).reshape(3,5,3)
Out[281]:
array([[[ 0, 5, 10],
[ 1, 6, 11],
[ 2, 7, 12],
[ 3, 8, 13],
[ 4, 9, 14]],
[[15, 20, 25],
[16, 21, 26],
[17, 22, 27],
[18, 23, 28],
[19, 24, 29]],
[[30, 35, 40],
[31, 36, 41],
[32, 37, 42],
[33, 38, 43],
[34, 39, 44]]])
Upvotes: 1
Reputation: 12407
You can simply swap axis you want before printing:
z = np.swapaxes(z, 1, 0)
for x in z:
for y in x:
print(y, end=' ')
print()
output:
z = np.arange(45).reshape(3,3,5)
#print(z)
[[[ 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]]]
#suggested code:
[0 1 2 3 4] [15 16 17 18 19] [30 31 32 33 34]
[5 6 7 8 9] [20 21 22 23 24] [35 36 37 38 39]
[10 11 12 13 14] [25 26 27 28 29] [40 41 42 43 44]
EDIT: per edit in question:
z = np.transpose(z,(0,2,1))
for x in z:
for y in x:
print(*y, end=' ')
print()
output:
0 5 10
1 6 11
2 7 12
3 8 13
4 9 14
15 20 25
16 21 26
17 22 27
18 23 28
19 24 29
30 35 40
31 36 41
32 37 42
33 38 43
34 39 44
Upvotes: 0