9

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)

2 Answers 2

21

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
Sign up to request clarification or add additional context in comments.

2 Comments

Though for the sake of my own sanity, could you explain the logic of what exactly this does for me? Trying to avoid cargo-cult coding.
Done - hope that makes sense
5

Using np.argmin is probably the best way to tackle this. To do it in pure python, you could use:

min(tuple(r[::-1]) for r in a)[::-1]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.