Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first occurence of elements in a numpy array

I have a numpy array:

a = np.array([-1,2,3,-1,5,-2,2,9])

I want to only keep values in the array which occurs more than 2 times, so the result should be:

a = np.array([-1,2,-1,2])

Is there a way to do this only using numpy? I have a solution using a dictionary and dictionary filtering, but this is kind of slow, and I was wondering if there was a faster solution only using numpy.

Thanks !

like image 792
BGR Avatar asked May 13 '26 11:05

BGR


1 Answers

import numpy as np
a = np.array([-1, 2, 3, -1, 5, -2, 2, 9])
values, counts = np.unique(a, return_counts=True)
values_filtered = values[counts >= 2]
result = a[np.isin(a, values_filtered)]
print(result)  # return [-1 2 -1 2]
like image 114
EL-AJI Oussama Avatar answered May 16 '26 01:05

EL-AJI Oussama



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!