Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the two smallest values from a numpy array

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?

like image 268
qasim Avatar asked May 16 '17 13:05

qasim


People also ask

How do I get indices of N minimum values in a NumPy array?

To get the indices of N miniumum values in NumPy in an optimal way, use the argpartition(~) method.


1 Answers

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
like image 62
MSeifert Avatar answered Oct 05 '22 13:10

MSeifert