Warm tip: This article is reproduced from serverfault.com, please click

python-查找数组中的三个最大元素

(python - Finding the three largest elements in an array)

发布于 2020-11-28 03:55:01

我有一个数组,其中包含4个随机生成的元素(使用Python):

pa = np.random.normal(10, 5, 4)

我可以通过执行以下操作找到最大的元素:

ml = np.max(pa)
mll = np.where(pa == ml)
print(mll)

我想知道如何在此数组中找到第二和第三元素?另外,我当前的输出看起来像:

(array([0]),)

有没有办法我可以获得纯数字输出(0)?谢谢!

更新:很抱歉,以前的困惑,我想找到第二和第三大元素的索引,但是到目前为止,所有答案对我都非常有帮助。谢谢!!

Questioner
ZR-
Viewed
0
Nick 2020-11-28 12:25:13

如果要使用四个值中的三个最大值,则可以找到所有大于最小值的值。你可以argwhere用来获取仅一个索引数组:

import numpy as np

pa = np.random.normal(10, 5, 4)
ml = np.min(pa)
mll = np.argwhere(pa > ml)
print(mll)

样本输出:

[[0]
 [1]
 [3]]

要展平该输出,请转换为数组,然后flatten

mll = np.array(np.nonzero(pa > ml)).flatten()
print(mll)

样本输出:

[0 1 3]