2016년 3월 24일 목요일

파이썬 기본함수 정렬 argsort

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] ------------------------------------------------------------- np.argsort doesn't sort the list in place, it returns a list full of indicies that you are able to use to sort the list. You must assign this returned list to a value: new_arr = np.argsort(arr) Then, to sort the list with such indices, you can do: np.array(arr)[new_arr] ------------------------------------------------------------- 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] ------------------------------------------------------------ x = numpy.array([1.48,1.41,0.0,0.1]) print x.argsort() >[2 3 1 0] 2 is the index of 0.0. •3 is the index of 0.1. •1 is the index of 1.41. •0 is the index of 1.48.

댓글 없음:

댓글 쓰기