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]])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With