【问题标题】:numpy: find index in sorted array (in an efficient way) [duplicate]numpy:在排序数组中查找索引(以一种有效的方式)[重复]
【发布时间】:2019-06-24 20:28:53
【问题描述】:

我想对一个 numpy 数组进行排序并找出每个元素的去向。

numpy.argsort 会告诉我排序数组中的每个索引,未排序数组中的哪个索引会在那里。我正在寻找类似相反的东西:对于未排序数组中的每个索引,它在排序数组中的位置。

a = np.array([1, 4, 2, 3])

# a sorted is [1,2,3,4]
# the 1 goes to index 0
# the 4 goes to index 3
# the 2 goes to index 1
# the 3 goes to index 2

# desired output
[0, 3, 1, 2]

# for comparison, argsort output
[0, 2, 3, 1]

一个简单的解决方案使用numpy.searchsorted

np.searchsorted(np.sort(a), a)
# produces [0, 3, 1, 2]

我对这个解决方案不满意,因为它看起来效率很低。它分两步进行排序和搜索。

这种奇特的索引对于有重复的数组会失败,请看:

a = np.array([1, 4, 2, 3, 5])
print(np.argsort(a)[np.argsort(a)])
print(np.searchsorted(np.sort(a),a))


a = np.array([1, 4, 2, 3, 5, 2])
print(np.argsort(a)[np.argsort(a)])
print(np.searchsorted(np.sort(a),a))

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    您可以在列表中使用两次argsort。 起初,这似乎有点令人困惑,但如果你仔细考虑一下,它就会开始变得有意义。

    a = np.array([1, 4, 2, 3])
    argSorted = np.argsort(a) # [0, 2, 3, 1]
    invArgSorted = np.argsort(argSorted) # [0, 3, 1, 2]
    

    【讨论】:

    • 您是否忘记将某些内容传递给argsort 的第二次调用?您可以通过解释它的工作原理以及它的意义来改进答案:)
    • 我和其他人在没有详细解释的情况下建议了这种双重 argsort。 stackoverflow.com/q/54388972/901925
    【解决方案2】:

    您只需要对数组进行排序的invert the permutation。如链接问题所示,您可以这样做:

    import numpy as np
    
    def sorted_position(array):
        a = np.argsort(array)
        a[a.copy()] = np.arange(len(a))
        return a
    
    print(sorted_position([0.1, 0.2, 0.0, 0.5, 0.8, 0.4, 0.7, 0.3, 0.9, 0.6]))
    # [1 2 0 5 8 4 7 3 9 6]
    

    【讨论】:

    • 很好,谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多