Changing an array size from 1D to 2D in a selective way

Viewed 63

I need to change my array from the following

Array = np.array([x1,y1,z1,x2,y2,z2......])

to

Array = [[x1,x2,x3......]
         [y1,y2,y3,.....]
         [z1,z2,z3,.....]]

Is this possible if so how ?

Thanks

3 Answers

You just need to reshape that 1D array to 2D, then transpose it.

import numpy as np

a = np.array([10, 11, 12, 20, 21, 22, 30, 31, 32, 40, 41, 42, 50, 51, 52])
a = a.reshape(-1, 3).T
print(a)

output

[[10 20 30 40 50]
 [11 21 31 41 51]
 [12 22 32 42 52]]

I think reshape could help you. See this docs: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.reshape.html

Is it what you were looking for ?

import numpy as np

foo = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8])
ret = [[], [], []]

for idx, number in enumerate(foo):
    ret[idx % 3].append(number)

print ret # out: [[0, 3, 6], [1, 4, 7], [2, 5, 8]]
Related