在 python 中获取 2d numpy 数组的前三个最大值

Get the first three largest values of a 2dnumpy array in python

嗨,我有一个 numpy 数组,例如

arr = np.random.rand(4,5)

array([[0.70733982, 0.1770464 , 0.55588376, 0.8810145 , 0.43711158],
       [0.22056565, 0.0193138 , 0.89995761, 0.75157581, 0.21073093],
       [0.22333035, 0.92795789, 0.3903581 , 0.41225472, 0.74992639],
       [0.92328687, 0.20438876, 0.63975818, 0.6179422 , 0.40596821]])

我需要在 array.I 中找到前三个最大的元素

arr[[-arr.argsort(axis=-1)[:, :3]]]

我还在 Whosebug 上提到了这个 question,它只给出索引而不是值

我可以得到前三个最大值的索引,但是如何得到它对应的值呢?

我还尝试通过转换为给定的列表来对数组进行排序 here

但没有给我所需的 result.Any 想法?

可以直接使用np.sort():

# np.sort sorts in ascending order
# --> we apply np.sort -arr
arr_sorted = -np.sort(-arr,axis=1)
top_three = arr_sorted[:,:3]

这个问题已经有了一个有效的可接受答案,但我只是想指出,在数组较大的情况下,使用 np.partition instead of np.sort 会快得多。我们仍然使用 np.sort,但仅用于构成我们 row-wise 前三名的数组的一小部分。

arr = np.random.random((10000, 10000))
top_three_fast = np.sort(np.partition(arr, -3)[:, -3:])[:, ::-1]

时间安排:

In [22]: %timeit top_three_fast = np.sort(np.partition(arr, -3)[:, -3:])[:, ::-1]
1.04 s ± 8.43 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [23]: %timeit top_three_slow = -np.sort(-arr, axis=1)[:, :3]
6.22 s ± 111 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [24]: (top_three_slow == top_three_fast).all()
Out[24]: True