0

This code snippet:

a = np.array([[1, 2], [0, 4], [3, 5]])
print(a[np.argmin(a[:, 0])])

prints coordinates of the point with minimum X coordinate from array a of points [x, y]:

[0 4]

Is there a more direct Numpy function than a[np.argmin(a[:, 0])] to accomplish the same task?

2
  • 1
    print(min(a, key=lambda x:x[0])) Commented Jan 31, 2022 at 18:19
  • 1
    I think the correct answer is "no"; your approach seems good. Using pure python instead of numpy for dubious syntax improvement will be inefficient in practice. Commented Feb 1, 2022 at 9:47

1 Answer 1

2

You can use the builtin min() function (i.e. not np.min()), which accepts an optional key argument, which is a function implementing how the comparison of elements is to be done. Here this would be

min(a, key=lambda point: point[0])

The point[0] simply extracts what you refer to as the x coordinate of each point. The returned value is the entire point for which point[0] is the minimum value.

Whether the above is "more direct" than a[np.argmin(a[:, 0])] is really up to you. They work in essential the same way; looping over a while keeping track of the so-far minimal point (as an index for np.argmin() and as a reference to the point for min()). Though both run in O(n) time, I'm confident that a[np.argmin(a[:, 0])] will be the fastest for large arrays.

For a more direct solution using NumPy, I don't think one exists. Even if NumPy contained a "np.minx()", this would certainly be implemented in a similar fashion and provide no additional benefits.

(Overly?) fancy implementation

In the above min() solution, we construct an anonymous function on the fly for the extraction of element 0. The standard library in fact contains a factory specifically for creating such functions:

import operator
min(a, key=operator.itemgetter(0))

Again this is equivalent, but may or may not look better on the page depending on preference :-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.