Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: Is there a way to compare two series and find elements that are recent in one series but not the other?

Tags:

python

pandas

I want to find out if there is a way to know numbers which are there in series B but not in Series A.

Series A:
[2,3,4,6,7]

Series B:
[4,5,6,7,8,9]

Output Expected:
[5,8,9]
like image 545
The Roy Avatar asked Sep 18 '25 23:09

The Roy


1 Answers

You can use pd.Series.isin with Boolean indexing:

A = pd.Series([2,3,4,6,7])
B = pd.Series([4,5,6,7,8,9])

res = B[~B.isin(A)].values

array([5, 8, 9], dtype=int64)

Or a NumPy variant:

res = B.values[~np.isin(B.values, A.values)]

You can also use set.difference:

res = list(set(B) - set(A))

[8, 9, 5]

Note, however, using built-ins with Pandas / NumPy is usually not optimal.

like image 120
jpp Avatar answered Sep 20 '25 14:09

jpp