numpy argsort 可以处理关系吗?

Bol*_*ain 6 python arrays sorting numpy

我有一个 numpy 数组:

foo = array([3, 1, 4, 0, 1, 0])
Run Code Online (Sandbox Code Playgroud)

我想要前 3 项。打电话

foo.argsort()[::-1][:3]
Run Code Online (Sandbox Code Playgroud)

返回

array([2, 0, 4])
Run Code Online (Sandbox Code Playgroud)

注意值foo[1]foo[4]是相等的,所以numpy.argsort()通过返回数组中最后出现的项目的索引来处理平局;即索引 4。

对于我的应用程序,我不能让平局总是偏向数组的末尾,那么我该如何实现随机平局呢?也就是说,一半的时间我会得到array([2, 0, 4]),另一半我会得到array([2, 0, 1])

cod*_*ior 4

这是一种方法:

用于numpy.unique对数组进行排序并删除重复的项目。传递return_inverse参数以获取已排序数组的索引,该索引给出原始数组的值。然后,您可以通过查找其值等于该项目的唯一数组的索引的逆数组的索引来获取绑定项目的所有索引。

例如:

foo = array([3, 1, 4, 0, 1, 0])
foo_unique, foo_inverse = unique(foo, return_inverse=True)

# Put largest items first
foo_unique = foo_unique[::-1]
foo_inverse = -foo_inverse + len(foo_unique) - 1

foo_top3 = foo_unique[:3]

# Get the indices into foo of the top item
first_indices = (foo_inverse == 0).nonzero()

# Choose one at random
first_random_idx = random.choice(first_indices)

second_indices = (foo_inverse == 1).nonzero()
second_random_idx = random.choice(second_indices)

# And so on...
Run Code Online (Sandbox Code Playgroud)

numpy.unique是使用 实现的argsort,因此看一下它的实现可能会建议一种更简单的方法。