1

So I have a Numpy Array with a bunch of numpy arrays inside of them. I want to group them based on the position in their individual array.

For Example: If Matrix is:

[[1, 2], [2, 3], [4, 5], [6, 7]]

Then the code should return:

[[1, 2, 4, 6], [2, 3, 5, 7]]

This is becuase 1, 2, 4, 6 are all the first elements in their individual arrays, and 2, 3, 5, 7 are the second elements in their individual arrays.

Anyone know some function that could do this. Thanks.

Answer in Python.

3

2 Answers 2

1

Using numpy transpose should do the trick:

a = np.array([[1, 2], [2, 3], [4, 5], [6, 7]])
a_t = a.T
print(a_t)
array([[1, 2, 4, 6],
       [2, 3, 5, 7]])
Sign up to request clarification or add additional context in comments.

Comments

0

Your data as a list:

In [101]: alist = [[1, 2], [2, 3], [4, 5], [6, 7]]                                             
In [102]: alist                                                                                
Out[102]: [[1, 2], [2, 3], [4, 5], [6, 7]]

and as a numpy array:

In [103]: arr = np.array(alist)                                                                
In [104]: arr                                                                                  
Out[104]: 
array([[1, 2],
       [2, 3],
       [4, 5],
       [6, 7]])

A standard idiom for 'transposing' lists is:

In [105]: list(zip(*alist))                                                                    
Out[105]: [(1, 2, 4, 6), (2, 3, 5, 7)]

with arrays, there's a transpose method:

In [106]: arr.transpose()                                                                      
Out[106]: 
array([[1, 2, 4, 6],
       [2, 3, 5, 7]])

The first array is (4,2) shape; its transpose is (2,4).

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.