Sorting a 2D numpy array by multiple axes

前端 未结 7 2063
小蘑菇
小蘑菇 2020-11-27 11:23

I have a 2D numpy array of shape (N,2) which is holding N points (x and y coordinates). For example:

array([[3, 2],
       [6, 2],
       [3, 6],
       [3,          


        
7条回答
  •  迷失自我
    2020-11-27 11:49

    You can use np.complex_sort. This has the side effect of changing your data to floating point, I hope that's not a problem:

    >>> a = np.array([[3, 2], [6, 2], [3, 6], [3, 4], [5, 3]])
    >>> atmp = np.sort_complex(a[:,0] + a[:,1]*1j)
    >>> b = np.array([[np.real(x), np.imag(x)] for x in atmp])
    >>> b
    array([[ 3.,  2.],
           [ 3.,  4.],
           [ 3.,  6.],
           [ 5.,  3.],
           [ 6.,  2.]])
    

提交回复
热议问题