Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

[[1,2,3],
[1,2,3],
[5,2,3]]

After the operation I would like to get this output

[[1,2,3],
[5,2,3]]

Obviously the second an third columns do not need to be unique.

Thanks

like image 246
Goerorge1237 Avatar asked Jan 02 '26 06:01

Goerorge1237


1 Answers

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]])
like image 180
Divakar Avatar answered Jan 03 '26 22:01

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!