Python, compare two numpy arrays, find groups and remove duplicates

Viewed 556

I have two arrays:

a = np.array([1,2,2,3,4,1,2,4,3,3])
b = np.array([100,200,200,100,400,100,200,400,100,100])

As you can see, there are two 1's in a and in the exact same indices, we can see two 100's in b. You can see three 3's in a and in the exact same indices, we can again see three 100's.
This can also be seen for the other numbers, i.e. 2 and 4.

I would like to compare these two arrays, get the groups, i.e. match 1 from a with the corresponding indices in b, and so on for the other numbers. Then I would like to eliminate all but first of each group in b, i.e.

result = np.array([100,200,100,400])

If the array b had unique group values (i.e. not repeating 100's for values 1 and 3 from array a), the problem would have been simply solved using np.unique. But since, two numbers from array a have the same group number in array b, I am finding it difficult.

1 Answers

Get the indices of the unique values in a and use these to get the corresponding values from b:

indices = np.unique(a, return_index=True)[1]
b[indices]

Result:

array([100, 200, 100, 400])
Related