how to search for unique elements by the first column of a multidimensional array

后端 未结 2 795
梦如初夏
梦如初夏 2020-12-12 00:35

I am trying to find a way how to create a new array from a multidimensional array by taking only elements that are unique in the first column, for example if I have an array

2条回答
  •  执念已碎
    2020-12-12 01:27

    Since you are looking to keep the first row of first column uniqueness, you can just use np.unique with its optional return_index argument which will give you the first occurring index (thus fulfils the first row criteria) among the uniqueness on A[:,0] elements, where A is the input array. Thus, we would have a vectorized solution, like so -

    _,idx = np.unique(A[:,0],return_index=True)
    out = A[idx]
    

    Sample run -

    In [16]: A
    Out[16]: 
    array([[1, 2, 3],
           [5, 2, 3],
           [1, 4, 3]])
    
    In [17]: _,idx = np.unique(A[:,0],return_index=True)
        ...: out = A[idx]
        ...: 
    
    In [18]: out
    Out[18]: 
    array([[1, 2, 3],
           [5, 2, 3]])
    

提交回复
热议问题