2016-11-28 111 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])