Skip to content Skip to sidebar Skip to footer

Python, Sort Array With Respect To A Sub-array

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 t

Solution 1:

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.]])

Post a Comment for "Python, Sort Array With Respect To A Sub-array"