7

I want to delete elements from array A that may be found in array B.

For example:

A = numpy.array([1, 5, 17, 28, 5])
B = numpy.array([3, 5])
C = numpy.delete(A, B)

C= [1, 17, 28]

1
  • 2
    @Prune: Please don't dupe-close a NumPy-tagged question with a list question as the dupe target. Commented Aug 29, 2018 at 17:07

5 Answers 5

14

Numpy has a function for that :

numpy.setdiff1d(A, B)

That will give you a new array with the result you expect.

More info on the sciPy documentation

Sign up to request clarification or add additional context in comments.

5 Comments

Is numpy the fastest solution?
Sure is, numpy has C code running for most of its features.
Thanks Maxime. System does not let be accept an answer yet. Got to wait 5 minutes.
Note that setdiff1d will sort the result and remove duplicates. If you don't want that, A[~numpy.isin(A, B)] will avoid the sort and deduplication, as long as A is actually an array and not the list you put in the question.
While a lot of numpy code is compiled, that's not true for all. You need to check the source to be sure. In this case setdiff1d uses np.unique and np.in1d which turn have Python code. It's heavily dependent on sorting.
7

You can try :

list(set(A)-set(B))
#[1, 28, 17]

Or a list comprehension :

[a for a in A if a not in B]

Another solution :

import numpy 
A[~numpy.isin(A, B)]
#array([ 1, 17, 28])

1 Comment

Might want to point out the set-based solution does not necessarily preserve the order of the elements in A.
4

Use a list-comprehension that iterates through A taking values that are not in B:

A = [1, 5, 17, 28, 5]
B = [3, 5]

print([x for x in A if x not in B])
# [1, 17, 28]

Comments

1

Try this

numpy.array([e for e in A if not e in B])

2 Comments

that's just copy of previous answers and adds no value
Sorry, the other answers didn't load on my phone.
1

You can also try :

V= [7,12,8,22,1]
N= [12,22,0,1,80,82,83,100,200,1000]
def test(array1, array2):
    A = array1
    B = array2
    c = []
    for a in range(len(A)):
        boolian=False
        for b in range(len(B)):
            if A[a]==B[b]:
                boolian=True
        if boolian==False:
            c.append(A[a])
    print(c)


test(V,N)

Comments

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.