Home > OS >  simplify and reform multidimensional python array
simplify and reform multidimensional python array

Time:06-08

I have got an array, which looks like this:

[array([[55.       ,  0.2443461]], dtype=float32), array([[-51.       ,   2.8972466]], dtype=float32), array([[-10.       ,   2.8972466]], dtype=float32), array([[221.       ,   0.2268928]], dtype=float32), array([[2.2000000e 02, 2.0943952e-01]], dtype=float32)]

I would like to change it in a way that gives me two arrays: one with the first value of each of the entries and one with the second.

So I want to the first array to look like this:

[55, -51, -10, 221, 1.2000000e 02]

And the second to look like this:

[0.2443461, 2.8972466, 2.8972466, 0.2268928, 2.0943952e-01]

I have found a way to do this using a loop, but I would like to avoid loops as much as possible, because the real arrays might be way bigger than the one I used in this example and if my code runs too slow I might get other problems. Is it possible to do it using indexing? If so: how?

The loop I used:

for x in range(lines_len):
        lines_angles.append(lines[x][0][1])
        lines_dist.append(lines[x][0][0])

CodePudding user response:

You have a list of np.arrays, but a list support only integer indices or slices. So, convert to an np.array before using three indices:

lines = np.array(lines)

lines_dist = lines[:,0,0]
 # [ 55. -51. -10. 221. 220.]

lines_angles = lines[:,0,1] 
 # [0.2443461  2.8972466  2.8972466  0.2268928  0.20943952]
  • Related