Find unique rows in numpy.array

后端 未结 20 2900
独厮守ぢ
独厮守ぢ 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条回答
  •  面向向阳花
    2020-11-21 11:42

    The most straightforward solution is to make the rows a single item by making them strings. Each row then can be compared as a whole for its uniqueness using numpy. This solution is generalize-able you just need to reshape and transpose your array for other combinations. Here is the solution for the problem provided.

    import numpy as np
    
    original = 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]])
    
    uniques, index = np.unique([str(i) for i in original], return_index=True)
    cleaned = original[index]
    print(cleaned)    
    

    Will Give:

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

    Send my nobel prize in the mail

提交回复
热议问题