Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete array from array

Tags:

python

numpy

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]

like image 605
Antonis Avatar asked Aug 29 '18 17:08

Antonis


People also ask

How do you remove an array from an array?

You can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically.

Can you delete an array?

Array elements can be deleted using the JavaScript operator delete . Using delete leaves undefined holes in the array. Use pop() or shift() instead.

How do I remove an item from an array index?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.


Video Answer


2 Answers

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

like image 151
Maxime B Avatar answered Sep 21 '22 17:09

Maxime B


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])
like image 28
Sruthi V Avatar answered Sep 20 '22 17:09

Sruthi V