Sorting a 2D numpy array by multiple axes

前端 未结 7 2080
小蘑菇
小蘑菇 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:52

    The title says "sorting 2D arrays". Although the questioner uses an (N,2)-shaped array, it's possible to generalize unutbu's solution to work with any (N,M) array, as that's what people might actually be looking for.

    One could transpose the array and use slice notation with negative step to pass all the columns to lexsort in reversed order:

    >>> import numpy as np
    >>> a = np.random.randint(1, 6, (10, 3))
    >>> a
    array([[4, 2, 3],
           [4, 2, 5],
           [3, 5, 5],
           [1, 5, 5],
           [3, 2, 1],
           [5, 2, 2],
           [3, 2, 3],
           [4, 3, 4],
           [3, 4, 1],
           [5, 3, 4]])
    
    >>> a[np.lexsort(np.transpose(a)[::-1])]
    array([[1, 5, 5],
           [3, 2, 1],
           [3, 2, 3],
           [3, 4, 1],
           [3, 5, 5],
           [4, 2, 3],
           [4, 2, 5],
           [4, 3, 4],
           [5, 2, 2],
           [5, 3, 4]])
    

提交回复
热议问题