简体   繁体   中英

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:

a = np.array([25, 2, 49, 3,90, 24, 45, 23, 9])
b = [3,45,23]
...

In order to get the 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. 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. 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. If not is there another way to remove the elements as I'm not to familiar with 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':-

indices=np.argwhere(np.isin(a,b))

Finally just delete those values by using delete() method:-

a=np.delete(a,indices)

Now if you print a you will get your desired output:-

array([25,  2, 49, 90, 24,  9])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM