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

后端 未结 2 793
梦如初夏
梦如初夏 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:22
    main = [[1, 2, 3], [1, 3, 4], [2, 4, 5], [3, 6, 5]]
    used = []
    new = [[sub, used.append(sub[0])][0] for sub in main if sub[0] not in used]
    print(new)
    # Output: [[1, 2, 3], [2, 3, 4], [3, 6, 5]]
    
    0 讨论(0)
  • 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]])
    
    0 讨论(0)
提交回复
热议问题