简体   繁体   中英

Sort numpy array by row and order matching values based on original array

I have a 2D numpy array and I would like to sort the rows based on first column values. The trouble is the way it is formatted:

Column I am sorting by: 0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,etc ->you can see it repeats itself

Basically I want to group the 1s, then 2s, then 3s, then 4s. The ordering of the matching values matter: I want the 1st '1' row to be the first one that appeared in the unsorted array, followed by the one that shows up next, etc. I use this command: sortedData= myData[myData[:,0].argsort()]

Unfortunately, it doesn't not appear to order matching columns based on the original ordering of the array. Are there certain options I can turn on to enable this?

Thanks!

You can change the sorting algorithm used by argsort with the kind argument.

Use

sortedData= myData[myData[:,0].argsort(kind='mergesort')]

to preserve the order of the equal items. ( Merge sort is a stable sorting algorithm.)

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