Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two numpy arrays and removing elements

Tags:

python

numpy

I have been going through several solutions, but I am not able to find a solution I need.

I have two numpy arrays. Let's take a small example here.

x = [1,2,3,4,5,6,7,8,9]
y = [3,4,5]

I want to compare x and y, and remove those values of x that are in y.

So I expect my final_x to be

final_x = [1,2,6,7,8,9]

I found out that np.in1d returns a boolean array the same length as x that is True where an element of x is in y and False otherwise. But how do I use it, if not any other method to get my final_x.??

like image 995
user3397243 Avatar asked Apr 07 '26 11:04

user3397243


2 Answers

If you really do have numpy arrays then you can use numpy.setdiff1d as below

import numpy as np

x = np.array([1,2,3,4,5,6,7,8,9])
y = np.array([3,4,5])

z = np.setdiff1d(x, y)
# array([1, 2, 6, 7, 8, 9])
like image 65
Ffisegydd Avatar answered Apr 09 '26 00:04

Ffisegydd


Simply pass the negated version of boolean array returned by np.in1d to array x:

>>> x = np.array([1,2,3,4,5,6,7,8,9])
>>> y = [3,4,5]
>>> x[~np.in1d(x, y)]
array([1, 2, 6, 7, 8, 9])
like image 30
Ashwini Chaudhary Avatar answered Apr 08 '26 23:04

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!