I have 2 lists(pandas.core.series.Series) and I want to list elements that doesn't exist in the other series. So I'm using 'not in' operator but it doesn't work and the code prints the whole list instead.
for i in list1:
if i not in list2:
print(i)
This code prints the whole list1 instead of printing elements that don't exist in list2. I know this should be a simple task but I'm stuck, can someone help me?
CodePudding user response:
You can use Pandas own Series.isin()
:
list1[~list1.isin(list2)]
CodePudding user response:
You can just use sets and calculate the set difference.
set(list1).difference(set(list2))
CodePudding user response:
I demonstrate isin using ~ which means not in. The isin build a mask of true of false values then applied to the dataframe
list1 = pd.Series([1, 2, 3, 4, 5])
list2 = pd.Series([4, 5, 6, 7, 8])
print(list1[~list1.isin(list2)])
output
1 2 3
values of list1 are not in list2