简体   繁体   中英

numpy array distance matrix ascending order, same to indices

I have both numpy array which is distances and indices

Image 1 - indices

Image 2 - distances

Let say I want to sort the distances into ascending order which is smallest to biggest values, but I also want to ensure the indices array follow back the order after the distances sorted.

the result of distances array after sorted

the result of indices follow back the order of distances array after sorted

My question here is I know how to sort the distances array by ascending order, but I don't know how to make the indices also follow the order after the distances sorted.

I think np.argsort is what you're after. It returns the indices that would sort a given array. You can use it to determine the indices that would sort your distances, then use this array to sort both the distances and the indices:

import numpy as np

distances = np.random.rand(20)
indices = np.random.rand(20)

sorter = np.argsort(distances)
distancse = distances[sorter]
indices = indices[sorter]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM