简体   繁体   中英

Python - Get the min coordinate element of a 2d numpy array

I have this 2d numpy array: [[0,2],[0,3],[0,1],[1,0]] . These elements represent points in x and y axes. So, for example, in [0,2] 0 is the x and 2 is the y .

I would like to get the point with the min x and min y . In this case, it would be [0,1] . I know I can easily do this with a for loop, but it takes too many resources. Is there a numpy function or something to calculate this?

You can first find the min of x , then find the min of y for pair where x equals the min of x :

np.min(xy[xy[:, 0] == np.min(xy[:, 0])], 0)
In [1]: xy
Out[1]: 
array([[0, 2],
       [0, 3],
       [0, 1],
       [1, 0]])

In [2]: np.min(xy[xy[:, 0] == np.min(xy[:, 0])], 0)
Out[2]: array([0, 1])

It is relatively fast, even for large array:

In [4]: timeit.timeit('np.min(xy[xy[:, 0] == np.min(xy[:, 0])], 0)',
                      'import numpy as np; xy = np.random.rand(100000, 2)', 
                      number = 100)
Out[4]: 0.06858562525758316

Old version which was a bit slower (before @OliverW. comment):

In [3]: timeit.timeit('np.min(xy[xy[:, 0] == np.min(xy, 0)[0]], 0)', 
                      'import numpy as np; xy = np.random.rand(100000, 2)', 
                      number = 100)
Out[3]: 0.20433111706540785

You can use the NumPy built-in np.lexsort to do such a sorting, like so -

xy[np.lexsort(xy.T[::-1])[0]]

lexsort gets the sorted indices that respects such a precedence, but does so in the opposite sense, ie the last element, then the second last element and so on until the first element. So, we need to reverse the order of elements, that's why the appended [::-1] . Also, lexsort works along each column instead of each row as needed to solve our case, so we needed that transpose before reversing.

Sample run -

In [235]: xy
Out[235]: 
array([[0, 2],
       [0, 3],
       [0, 1],
       [1, 0]])

In [236]: xy[np.lexsort(xy.T[::-1])[0]]
Out[236]: array([0, 1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM