5

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

1 Answer 1

6

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])
Sign up to request clarification or add additional context in comments.

1 Comment

@YashvanderBamel Everything is wrong....as if you don't know the position of values of b that are present in a then how can you delete it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.