Find unique rows in numpy.array

后端 未结 20 2902
独厮守ぢ
独厮守ぢ 2020-11-21 10:57

I need to find unique rows in a numpy.array.

For example:

>>> a # I have
array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
         


        
20条回答
  •  猫巷女王i
    2020-11-21 11:52

    For general purpose like 3D or higher multidimensional nested arrays, try this:

    import numpy as np
    
    def unique_nested_arrays(ar):
        origin_shape = ar.shape
        origin_dtype = ar.dtype
        ar = ar.reshape(origin_shape[0], np.prod(origin_shape[1:]))
        ar = np.ascontiguousarray(ar)
        unique_ar = np.unique(ar.view([('', origin_dtype)]*np.prod(origin_shape[1:])))
        return unique_ar.view(origin_dtype).reshape((unique_ar.shape[0], ) + origin_shape[1:])
    

    which satisfies your 2D dataset:

    a = np.array([[1, 1, 1, 0, 0, 0],
           [0, 1, 1, 1, 0, 0],
           [0, 1, 1, 1, 0, 0],
           [1, 1, 1, 0, 0, 0],
           [1, 1, 1, 1, 1, 0]])
    unique_nested_arrays(a)
    

    gives:

    array([[0, 1, 1, 1, 0, 0],
       [1, 1, 1, 0, 0, 0],
       [1, 1, 1, 1, 1, 0]])
    

    But also 3D arrays like:

    b = np.array([[[1, 1, 1], [0, 1, 1]],
                  [[0, 1, 1], [1, 1, 1]],
                  [[1, 1, 1], [0, 1, 1]],
                  [[1, 1, 1], [1, 1, 1]]])
    unique_nested_arrays(b)
    

    gives:

    array([[[0, 1, 1], [1, 1, 1]],
       [[1, 1, 1], [0, 1, 1]],
       [[1, 1, 1], [1, 1, 1]]])
    

提交回复
热议问题