问题
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]
I get this error:
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?
回答1:
You can use numpy.partition to get the lowest k+1
items:
A, B = np.partition(x, 1)[0:2] # k=1, so the first two are the smallest items
In Python 3.x you could also use:
A, B, *_ = np.partition(x, 1)
For example:
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
回答2:
How about using sorted
instead of np.where
?
A,B = sorted(x)[:2]
回答3:
There are two errors in the code. The first is that the slice is [0:1]
when it should be [0:2]
. The second is actually a very common issue with np.where
. If you look into the documentation, you will see that it always returns a tuple, with one element if you only pass one parameter. Hence you have to access the tuple element first and then index the array normally:
A,B = np.where(x == x.min())[0][0:2]
Which will give you the two first indices containing the minimum value. If no two such indices exist you will get an exception, so you may want to check for that.
来源:https://stackoverflow.com/questions/44002239/how-to-get-the-two-smallest-values-from-a-numpy-array