Jonny
Jonny

Reputation: 1368

Minimum x and y coordinate of 2d array. Python

I have a nx2 array where the first column represents x-coordinates and the second column y-coordinates, for example:

array = np.array([0,3],
                 [1,5],
                 [2,1],
                 [3,2])

How can I obtain the minimum y-coordinate with the corresponding x-coordinate returned allong with it? In the example, I want [1,2] returned, where 2 is the row index, not the numerical value contained in the array, but 1 is the actual numerical value.

I know I can simply use np.amin(array[:,1]) to obtain the minimum y-coordinate, but this doesn't give me any info of what x-coordinate corresponds to the y-minimum.

I have looked at the documentation of np.amin to see if it can return two parameters but it does not look like it can.

Upvotes: 1

Views: 1969

Answers (2)

Back2Basics
Back2Basics

Reputation: 7806

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

You want to reference array values like this in a 2d array.

array[column][row]

np.argmin will give you the smallest number's index in the column and array*[0] will give the first element in the row

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

Perhaps something like this:

>>> index = array[:, 1].argmin()
>>> np.unravel_index((index * 2) + 1, array.shape)
(2, 1)
# reverse to get the column index first.
>>> np.unravel_index((index * 2) + 1, array.shape)[::-1]
(1, 2)

Upvotes: 1

Related Questions