5

我尝试对数组进行排序:

import numpy as np

arr = [5,3,7,2,6,34,46,344,545,32,5,22]
print "unsorted"
print arr

np.argsort(arr)

print "sorted"
print arr

但输出是:

unsorted
[5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22]
sorted
[5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22]

数组完全没有变化

4

4 回答 4

23

np.argsort不会对列表进行适当的排序,它会返回一个列表,其中包含您可以用来对列表进行排序的索引。

您必须将此返回的列表分配给一个值:

new_arr = np.argsort(arr)

然后,要使用此类索引对列表进行排序,您可以执行以下操作:

np.array(arr)[new_arr]
于 2013-11-06T04:25:40.497 回答
7

There are two issues here; one is that np.argsort returns an array of the indices which would sort the original array, the second is that it doesn't modify the original array, just gives you another. This interactive session should help explain:

In [59]: arr = [5,3,7,2,6,34,46,344,545,32,5,22]

In [60]: np.argsort(arr)
Out[60]: array([ 3,  1,  0, 10,  4,  2, 11,  9,  5,  6,  7,  8])

Above, the [3, 1, 0, ...] means that item 3 in your original list should come first (the 2), then item 2 should come (the 3), then the first (index is 0, item is 5) and so on. Note that arr is still unaffected:

In [61]: arr
Out[61]: [5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22]

You might not need this array of indices, and would find it easier to just use np.sort:

In [62]: np.sort(arr)
Out[62]: array([  2,   3,   5,   5,   6,   7,  22,  32,  34,  46, 344, 545])

But this still leaves arr alone:

In [68]: arr
Out[68]: [5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22]

If you want to do it in place (modify the original), use:

In [69]: arr.sort()

In [70]: arr
Out[70]: [2, 3, 5, 5, 6, 7, 22, 32, 34, 46, 344, 545]
于 2013-11-06T04:38:58.983 回答
7

尝试

order = np.argsort(arr)
print np.array(arr)[order]

argsort响应是元素的索引 。

于 2013-11-06T04:27:27.980 回答
2

If you want your array sorted in-place you want arr.sort():

In [1]: import numpy as np  
In [2]: arr = [5,3,7,2,6,34,46,344,545,32,5,22]

In [4]: print arr
[5, 3, 7, 2, 6, 34, 46, 344, 545, 32, 5, 22]

In [5]: arr.sort()
In [7]: print arr
[2, 3, 5, 5, 6, 7, 22, 32, 34, 46, 344, 545]
于 2013-11-06T04:38:11.683 回答