python numpy find y value based on x value

Viewed 41

I want to get column y that has maximum x value. If I have

arr = [[1, 1],[1, 2],[3, 0],[4, 7],[3, 1],[4, 6]]

Since the minimum x value is 1, I want the value 1 and 2. So far, I got the minimum x value by

min = np.amin(arr, axis=0)

but I don't know how to get the other value which has the min value

1 Answers

Use np.min to find the minimum x-coordinate and then boolean indexing to find all the matching values.

import numpy as np

arr = np.array([[1, 1], [1, 2], [3, 0], [4, 7], [3, 1], [4, 6]])

# find the minimum across the x coordinate
mi = np.min(arr[:, 0])

# find all the positions equals to the minimum using boolean indexing and get the y coordinate
res = arr[arr[:, 0] == mi, 1]

print(res)

Output

[1 2]

Note: Don't use min as a variable name because it shadows the built-in function.

Related