Removing duplicate columns and rows from a NumPy 2D array

后端 未结 6 1778
别那么骄傲
别那么骄傲 2020-11-29 04:55

I\'m using a 2D shape array to store pairs of longitudes+latitudes. At one point, I have to merge two of these 2D arrays, and then remove any duplicated entry. I\'ve been se

6条回答
  •  半阙折子戏
    2020-11-29 05:12

    This should do the trick:

    def unique_rows(a):
        a = np.ascontiguousarray(a)
        unique_a = np.unique(a.view([('', a.dtype)]*a.shape[1]))
        return unique_a.view(a.dtype).reshape((unique_a.shape[0], a.shape[1]))
    

    Example:

    >>> a = np.array([[1, 1], [2, 3], [1, 1], [5, 4], [2, 3]])
    >>> unique_rows(a)
    array([[1, 1],
           [2, 3],
           [5, 4]])
    

提交回复
热议问题