2016-11-28 115 views
1

支持假設我們定義一個函數用於支持做argsort爲紐帶as described in this solution:與他np.argsort與關係

input = np.array([5.5, 3.5, 2.0, 2.0, 7.0, 7.0, 7.0, 3.5, 6.5, 6.5, 6.5, 9.0]) 
output = argsort_with_support_for_ties(input) 

以下結果:

def argsort_with_support_for_ties(a): 
    rnd_array = np.random.random(a.size) 
    return np.lexsort((rnd_array,a)) 

我們測試它

> np.stack([input, output], axis=0).T 

array([[ 5.5, 3. ], 
     [ 3.5, 2. ], 
     [ 2. , 1. ], 
     [ 2. , 7. ], 
     [ 7. , 0. ], <--- A 
     [ 7. , 10. ], <--- B 
     [ 7. , 9. ], 
     [ 3.5, 8. ], 
     [ 6.5, 5. ], 
     [ 6.5, 4. ], 
     [ 6.5, 6. ], 
     [ 9. , 11. ]]) 

請注意條目AB共享相同的輸入值(7),但結束於極其不同的位置010

這不是我所希望得到的。更可以接受的答案會是:

output = np.array([4, 2, 1, 0, 8, 9, 10, 3, 5, 6, 7, 11]) 

那麼與argsort_with_support_for_ties上述失敗了嗎?

+1

看看'輸入[輸出]',它不給一個排序的數組? – wrwrwr

+1

您正在解釋'lexsort'的結果不正確。這不是價值的排名。它包含的索引是'input [output]'是排序後的數組。例如,結果顯示'output [4]'爲0.這意味着在排序結果中,索引4處的值取自索引0處的輸入。 –

+1

如果要對這些值排序,請參見http:/ /stackoverflow.com/questions/5284646/rank-items-in-an-array-using-python-numpy –

回答

1

我知道你想排名的元素,以便tiebreaking是隨機的。對於這一點,你只需要翻轉你從lexsort得到了排列:

output = np.argsort(np.lexsort((rnd_array,a))) 

我的輸出(這是不相同的,因爲隨機性的你):

array([ 4, 3, 0, 1, 10, 9, 8, 2, 7, 5, 6, 11])