按行对numpy数组排序,并根据原始数组对匹配值进行排序 [英] Sort numpy array by row and order matching values based on original array
问题描述
我有一个2D numpy数组,我想根据第一列的值对行进行排序.麻烦的是它的格式化方式:
我按以下顺序对列进行排序:0、1、2、3、4、0、1、2、3、4、0、1、2、3、4等->您可以看到它重复出现了>
基本上,我想将1s,2s,3s,4s分组.匹配值的顺序很重要:我希望第1个"1"行成为未排序数组中的第一个行,然后是接下来显示的行,依此类推.我使用此命令: sortedData = myData [myData [:,0] .argsort()]
不幸的是,它似乎没有根据数组的原始顺序对匹配的列进行排序.我可以启用某些选项来启用此功能吗?
谢谢!
您可以更改合并排序是一种稳定排序算法.)
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.)
这篇关于按行对numpy数组排序,并根据原始数组对匹配值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!