[英]Remove first occurence of elements in a numpy array
I have a numpy array:我有一个 numpy 数组:
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:我只想将出现次数超过 2 次的值保留在数组中,因此结果应该是:
a = np.array([-1,2,-1,2])
Is there a way to do this only using numpy?有没有办法只使用 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.我有一个使用字典和字典过滤的解决方案,但这有点慢,我想知道是否有仅使用 numpy 的更快的解决方案。
Thanks !谢谢 !
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]
import numpy as np
arr = np.array([1, 2, 3,4,4,4,1])
filter_arr = [np.count_nonzero(arr == i)>1 for i in arr]
newarr = arr[filter_arr]
print(filter_arr)
print(np.unique(newarr))
Here's one way using broadcasting and some advanced indexing techniques:这是使用广播和一些高级索引技术的一种方法:
In [24]: a[(a[:, None] == a).sum(0) > 1]
Out[24]: array([-1, 2, -1, 2])
thanks a lot!多谢!
All answers solved the problem, but the solution from Matvey_coder3 was the fastest.所有答案都解决了问题,但 Matvey_coder3 的解决方案是最快的。
KR韩国
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.