简体   繁体   English

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

[英]How to get the two smallest values from a numpy array

I would like to take the two smallest values from an array x .我想从数组x获取两个最小值。 But when I use np.where :但是当我使用np.where

A,B = np.where(x == x.min())[0:1]

I get this error:我收到此错误:

ValueError: need more than 1 value to unpack ValueError:需要 1 个以上的值才能解包

How can I fix this error?我该如何解决这个错误? And do I need to arange numbers in ascending order in array?我是否需要在数组中按升序排列数字?

You can use numpy.partition to get the lowest k+1 items:您可以使用numpy.partition获得最低的k+1项:

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:在 Python 3.x 中,您还可以使用:

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

使用sorted而不是np.where怎么np.where

A,B = sorted(x)[:2]

There are two errors in the code.代码中有两个错误。 The first is that the slice is [0:1] when it should be [0:2] .第一个是切片是[0:1]而应该是[0:2] The second is actually a very common issue with np.where .第二个实际上是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.如果不存在两个这样的索引,您将得到一个例外,因此您可能需要检查一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM