如何从numpy数组中获取两个最小值 [英] How to get the two smallest values from a numpy array
本文介绍了如何从numpy数组中获取两个最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从数组 x
中获取两个最小值.但是当我使用 np.where
:
I would like to take the two smallest values from an array x
. But when I use np.where
:
A,B = np.where(x == x.min())[0:1]
我收到此错误:
ValueError:需要超过1个值才能解包
ValueError: need more than 1 value to unpack
如何解决此错误?我是否需要在数组中按升序排列数字?
How can I fix this error? And do I need to arange numbers in ascending order in array?
推荐答案
您可以使用在Python 3.x中,您还可以使用:
In Python 3.x you could also use:
A, B, *_ = np.partition(x, 1)
例如:
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
这篇关于如何从numpy数组中获取两个最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文