0

I have the following array:

master_array = [[1. 2. 3. 4. 5.]
                [9. 8. 4. 5. 1.]]

I would like to sort the master_array with respect to the second sub-array so that the relationship between first sub-array and second sub-array is maintained

master_array = [[5. 3. 4. 2. 1.] 
                [1. 4. 5. 8. 9.]]

Thank You

4
  • Why is this tagged with numpy? What you are showing here is a list. Commented Jan 24, 2018 at 8:18
  • So, I tried searching how to arrange an array with respect to a sub-array, was not able to find anything substantial yet. Sorry, forgot the dots after the numbers. Commented Jan 24, 2018 at 8:21
  • what are those dots mean ? Commented Jan 24, 2018 at 8:51
  • That's how array is constructed. Commented Jan 24, 2018 at 8:58

1 Answer 1

2

Convert list to numpy array

>>> import numpy as np
>>> master_array = [[1.,2.,3.,4.,5.], [9.,8.,4.,5.,1.]]
>>> n=np.array(master_array)
>>> n
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 9.,  8.,  4.,  5.,  1.]])

Assign index values for the second array so take n[1]

>>> temp=list(enumerate(n[1]))
>>> temp
[(0, 9.0), (1, 8.0), (2, 4.0), (3, 5.0), (4, 1.0)]

sort the array with respect to array elements

>>> list1=sorted(temp,key=lambda x:x[1])
>>> list1
[(4, 1.0), (2, 4.0), (3, 5.0), (1, 8.0), (0, 9.0)]

Take all the indexes from sorted result and store in a seperate array

>>> a=[i[0] for i in list1 ]
>>> a
[4, 2, 3, 1, 0]

Use indexing of columns in numpy on the numpy array

>>> n[:,a]
array([[ 5.,  3.,  4.,  2.,  1.],
       [ 1.,  4.,  5.,  8.,  9.]])
Sign up to request clarification or add additional context in comments.

3 Comments

That's beautiful! Do you mind explaining what each of the steps does?
@IsaacA i have modified the answer pls check
Hello Paul, that's quite a brilliant solution. Thank you for your help. Explanations make sense. I found the last part to be somewhat challenging, but after some thinking I understood what is happening.

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.