[英]removing elements from a numpy array based on elements of another array
How would I go about removing elements from an array based on the contents of another array for example:我将如何 go 关于根据另一个数组的内容从数组中删除元素,例如:
a = np.array([25, 2, 49, 3,90, 24, 45, 23, 9])
b = [3,45,23]
...
In order to get the output:为了获得 output:
>>>a
25, 2, 49,90,24, 9
It doesn't really matter to me if b is a regular list or a numpy array.如果 b 是常规列表或 numpy 数组,对我来说并不重要。 I've seen lots of similar questions but they all remove array elements based on index or if they do remove them based on the element the list gets sorted as a result eg by using np.setdiff1d.
我见过很多类似的问题,但它们都基于索引删除数组元素,或者如果它们确实基于元素删除它们,则列表作为结果进行排序,例如使用 np.setdiff1d。 I want to know if there are any numpy methods that will let me do something similar to np.setdiff1d but without sorting the array.
我想知道是否有任何 numpy 方法可以让我做类似于 np.setdiff1d 但不对数组进行排序的事情。 If not is there another way to remove the elements as I'm not to familiar with numpy.
如果没有,还有其他方法可以删除元素,因为我不熟悉 numpy。 Thanks in advance
提前致谢
Just make use of argwhere()
method to find the indices of those values of 'b' that are present in 'a' and isin()
method to check the values inside 'b' is present in 'a':-只需使用
argwhere()
方法来查找存在于 'a' 中的那些 'b' 值的索引,并使用 isin( isin()
方法来检查 'b' 内的值是否存在于 'a' 中:-
indices=np.argwhere(np.isin(a,b))
Finally just delete those values by using delete()
method:-最后只需使用
delete()
方法删除这些值:-
a=np.delete(a,indices)
Now if you print a
you will get your desired output:-现在,如果您打印
a
您将获得所需的 output:-
array([25, 2, 49, 90, 24, 9])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.