【问题标题】:np.argsort with support for tiesnp.argsort 支持关系
【发布时间】: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. ]])

请注意条目 AB 如何共享相同的输入值 (7),但最终位于完全不同的位置 010

这不是我希望得到的。更可接受的答案是:

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


【解决方案1】:

我了解您希望对元素进行排名,以便平局是随机的。为此,您只需反转从lexsort 获得的排列:

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

我的输出(由于随机性与您的输出不同):

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

【讨论】:

    猜你喜欢
    • 2011-08-09
    • 2018-04-06
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多