Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort one array by columns of another array - Python

I have two arrays, a and b, as follows:

a = array([[19.        ,  0.84722222],
           [49.        ,  0.86111111],
           [54.        ,  0.86666667],
           [42.        ,  0.9       ],
           [ 7.        ,  0.91111111],
           [46.        ,  0.99722222]])

b = array([[46.        ,  0.46944444],
       [49.        ,  0.59722222],
       [19.        ,  0.63611111],
       [42.        ,  0.72777778],
       [54.        ,  0.74722222],
       [ 7.        ,  0.98888889]])

I would like to sort b so that its first column matches the first column of array a. My output should be

b = array([[19.        ,  0.63611111],
           [49.        ,  0.59722222],
           [54.        ,  0.74722222],
           [42.        ,  0.72777778],
           [ 7.        ,  0.98888889]
           [46.        ,  0.46944444]])
like image 253
Silvia Sanna Avatar asked Jan 21 '26 03:01

Silvia Sanna


1 Answers

Conceptually you want to get the indices that will turn column zero of b into column zero of a. Imagine doing argsort on both. This will give you the indices to go from a or b to a sorted state. Now if you apply the inverse operation to the a index, it will tell you how to get from sorted back to a. As it happens, argsort is its own inverse. So I present you the following:

index = np.argsort(b[:, 0])[np.argsort(np.argsort(a[:, 0]))]
b = b[index, ...]

This is O(n log n) time complexity because of the three sorts. The other solutions here are O(n^2) since they perform a linear search for each index.

like image 98
Mad Physicist Avatar answered Jan 22 '26 17:01

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!