【问题标题】:Get the first three largest values of a 2dnumpy array in python在python中获取2dnumpy数组的前三个最大值
【发布时间】:2019-07-12 08:37:46
【问题描述】:

嗨,我有一个 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]])

我需要找到数组中前三个最大的元素。我试过了

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

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

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

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

但没有给我所需的结果。有什么想法吗?

【问题讨论】:

标签: python arrays sorting numpy-ndarray


【解决方案1】:

你可以直接使用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]

【讨论】:

  • 抱歉,我需要 numpy 数组每一行的前 3 个值
  • 只是想知道 '-' 在这里有什么作用?如果它的列表列表有没有办法?
  • 默认情况下,np.sort 按升序排序。通过反转登录排序,您可以获得降序。然后,您得到正确的顺序,但所有负数。所以你需要恢复标志。如果您有列表列表,则可以转换为 numpy 并执行相同操作
  • 你可以通过top_three = np.sort(arr, axis=1)[:, -3:]避免负号
【解决方案2】:

这个问题已经有一个有效的可接受答案,但我只是想指出,在更大的数组的情况下,使用np.partition 而不是np.sort 会快得多。我们仍然使用np.sort,但仅在构成我们按行排列的前三名的数组的小子集上使用。

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

【讨论】:

    猜你喜欢
    • 2017-04-18
    • 2022-07-27
    • 1970-01-01
    • 2021-04-04
    • 2013-03-15
    • 1970-01-01
    • 2015-10-13
    • 2022-01-13
    • 1970-01-01
    相关资源
    最近更新 更多