如何从numpy数组中获取两个最小值

qas*_*sim 5 python arrays numpy

我想从数组中获取两个最小值x。但是当我使用时np.where

A,B = np.where(x == x.min())[0:1]
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

ValueError:需要多个值才能解压

如何解决此错误?我是否需要在数组中按升序排列数字?

MSe*_*ert 5

您可以numpy.partition用来获取最低的k+1项目:

A, B = np.partition(x, 1)[0:2]  # k=1, so the first two are the smallest items
Run Code Online (Sandbox Code Playgroud)

在Python 3.x中,您还可以使用:

A, B, *_ = np.partition(x, 1)
Run Code Online (Sandbox Code Playgroud)

例如:

import numpy as np
x = np.array([5, 3, 1, 2, 6])
A, B = np.partition(x, 1)[0:2]
print(A)  # 1
print(B)  # 2
Run Code Online (Sandbox Code Playgroud)