Paul Jurczak
Paul Jurczak

Reputation: 8165

Get point with minimum x from 2D numpy array of points

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?

Upvotes: 0

Views: 1294

Answers (1)

jmd_dk
jmd_dk

Reputation: 13100

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 :-)

Upvotes: 2

Related Questions