w3resource

Pandas Data Series: Get the items of a given series not present in another given series


Write a Pandas program to get the items of a given series not present in another given series.

Sample Solution :

Python Code :

import pandas as pd
sr1 = pd.Series([1, 2, 3, 4, 5])
sr2 = pd.Series([2, 4, 6, 8, 10])
print("Original Series:")
print("sr1:")
print(sr1)
print("sr2:")
print(sr2)
print("\nItems of sr1 not present in sr2:")
result = sr1[~sr1.isin(sr2)]
print(result)

Sample Output:

Original Series:
sr1:
0    1
1    2
2    3
3    4
4    5
dtype: int64
sr2:
0     2
1     4
2     6
3     8
4    10
dtype: int64

Items of sr1 not present in sr2:
0    1
2    3
4    5
dtype: int64                

Explanation:

sr1 = pd.Series([1, 2, 3, 4, 5])
sr2 = pd.Series([2, 4, 6, 8, 10])

Above code creates two Pandas Series objects 'sr1' and 'sr2', each containing a sequence of five integer values.

result = sr1[~sr1.isin(sr2)]: This line creates a new Pandas Series object 'result' by selecting the elements from the original Series object 'sr1' that are not in the Series object 'sr2'. This is done by applying a boolean mask to the original Series object using the .isin() method to check which elements in 'sr1' are present in 'sr2', and then negating the boolean mask using the tilde (~) operator.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to create the mean and standard deviation of the data of a given Series.
Next: Write a Pandas program to get the items which are not common of two given series.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.