1

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!

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Simple and effective!!!
0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.