【发布时间】:2016-11-28 23:00:55
【问题描述】:
假设我们定义了一个函数来执行argsort 并支持关系as described in this solution:
def argsort_with_support_for_ties(a):
rnd_array = np.random.random(a.size)
return np.lexsort((rnd_array,a))
我们测试它:
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)
结果如下:
> 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. ]])
请注意条目 A 和 B 如何共享相同的输入值 (7),但最终位于完全不同的位置 0 和 10。
这不是我希望得到的。更可接受的答案是:
output = np.array([4, 2, 1, 0, 8, 9, 10, 3, 5, 6, 7, 11])
那么上面argsort_with_support_for_ties 失败的原因是什么?
【问题讨论】:
-
看看
input[output],是不是给出了一个排序好的数组? -
您错误地解释了
lexsort的结果。这不是价值观的排名。它保存索引,使得input[output]是排序数组。例如,您的结果显示output[4]为 0。这意味着在排序结果中,索引 4 处的值取自索引 0 处的输入。 -
如果要对值进行排名,请参阅stackoverflow.com/questions/5284646/…
标签: python-3.x sorting numpy