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]

Antonis
  • 361
  • 2
  • 4
  • 11

5 Answers5

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

Maxime B
  • 966
  • 1
  • 9
  • 30
  • Is numpy the fastest solution? – Antonis Aug 29 '18 at 17:05
  • Sure is, numpy has C code running for most of its features. – Maxime B Aug 29 '18 at 17:08
  • Thanks Maxime. System does not let be accept an answer yet. Got to wait 5 minutes. – Antonis Aug 29 '18 at 17:10
  • 3
    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. – user2357112 Aug 29 '18 at 17:14
  • 1
    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. – hpaulj Aug 29 '18 at 17:19
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])
Sruthi
  • 2,908
  • 1
  • 11
  • 25
  • 4
    Might want to point out the `set`-based solution does not necessarily preserve the order of the elements in `A`. – Ray Toal Aug 29 '18 at 17:03
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]
Austin
  • 25,759
  • 4
  • 25
  • 48
1

Try this

numpy.array([e for e in A if not e in B])
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
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)