Antonis
Antonis

Reputation: 361

Delete array from array

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]

Upvotes: 7

Views: 16718

Answers (5)

user10273157
user10273157

Reputation:

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)

Upvotes: 1

Sruthi
Sruthi

Reputation: 3018

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])

Upvotes: 7

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

Try this

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

Upvotes: 1

Maxime B
Maxime B

Reputation: 1016

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

Upvotes: 14

Austin
Austin

Reputation: 26047

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]

Upvotes: 4

Related Questions