Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row

Tags:

python

numpy

Consider the following NumPy array:

a = np.array([[1,4], [2,1],(3,10),(4,8)])

This gives an array that looks like the following:

array([[ 1,  4],
       [ 2,  1],
       [ 3, 10],
       [ 4,  8]])

What I'm trying to do is find the minimum value of the second column (which in this case is 1), and then report the other value of that pair (in this case 2). I've tried using something like argmin, but that gets tripped up by the 1 in the first column.

Is there a way to do this easily? I've also considered sorting the array, but I can't seem to get that to work in a way that keeps the pairs together. The data is being generated by a loop like the following, so if there's a easier way to do this that isn't a numpy array, I'd take that as an answer too:

results = np.zeros((100,2))

# Loop over search range, change kappa each time
for i in range(100):
    results[i,0] = function1(x)
    results[i,1] = function2(y)
like image 423
Fomite Avatar asked Feb 19 '13 11:02

Fomite


1 Answers

How about

a[np.argmin(a[:, 1]), 0]

Break-down

a. Grab the second column

>>> a[:, 1]
array([ 4,  1, 10,  8])

b. Get the index of the minimum element in the second column

>>> np.argmin(a[:, 1])
1

c. Index a with that to get the corresponding row

>>> a[np.argmin(a[:, 1])]
array([2, 1])

d. And take the first element

>>> a[np.argmin(a[:, 1]), 0]
2
like image 133
YXD Avatar answered Oct 26 '22 14:10

YXD