Home > Blockchain >  Merge numpy arrays contained in another array into different numpy array
Merge numpy arrays contained in another array into different numpy array

Time:10-23

I'm working on numpy to manage different array. I have a python function that returns to me this array of arrays:

res = [[[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]]]

What i desired to extract from this res variable is this one:

a = [1 2 1 2 1 2 1 2 1 2]
b = [5 6 5 6 5 6 5 6 5 6]
c = [7 8 7 8 7 8 7 8 7 8]

The idea is to extract and merge the first array of each array into a, the second arrays to b and so on.

Could you please help me to achieve this result? Thanks a lot!

CodePudding user response:

You can use numpy.hstack then use tuple unpacking.

In [7]: a, b, c = np.hstack(res)                                                

In [8]: a                                                                       
Out[8]: array([1, 2, 1, 2, 1, 2, 1, 2, 1, 2])

In [9]: b                                                                       
Out[9]: array([5, 6, 5, 6, 5, 6, 5, 6, 5, 6])

In [10]: c                                                                      
Out[10]: array([7, 8, 7, 8, 7, 8, 7, 8, 7, 8])

CodePudding user response:

Given:

import numpy as np

res = np.array([[[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]], [[1, 2], [5, 6], [7, 8]]])

a = res[:, 0]
b = res[:, 1]
c = res[:, 2]

print(a)
print(b)
print(c)

Output:

[[1 2]
 [1 2]
 [1 2]
 [1 2]
 [1 2]]
[[5 6]
 [5 6]
 [5 6]
 [5 6]
 [5 6]]
[[7 8]
 [7 8]
 [7 8]
 [7 8]
 [7 8]]

Or:

print(a.flatten())
print(b.flatten())
print(c.flatten())

Output:

[1 2 1 2 1 2 1 2 1 2]
[5 6 5 6 5 6 5 6 5 6]
[7 8 7 8 7 8 7 8 7 8]
  • Related