Pandas Data Series: Get the items which are not common of two given series
Pandas: Data Series Exercise-17 with Solution
Write a Pandas program to get the items which are not common of two given series.
Sample Solution :
Python Code :
import pandas as pd
import numpy as np
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 a given series not present in another given series:")
sr11 = pd.Series(np.union1d(sr1, sr2))
sr22 = pd.Series(np.intersect1d(sr1, sr2))
result = sr11[~sr11.isin(sr22)]
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 a given series not present in another given series: 0 1 2 3 4 5 5 6 6 8 7 10 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.
sr11 = pd.Series(np.union1d(sr1, sr2)): This line creates a new Pandas Series object 'sr11' by taking the union of the values in the original Series objects 'sr1' and 'sr2' using the np.union1d() function. This will result in a new Series object 'sr11' containing all the unique values present in either Series object 'sr1' or 'sr2'.
sr22 = pd.Series(np.intersect1d(sr1, sr2)): This line creates a new Pandas Series object 'sr22' by taking the intersection of the values in the original Series objects 'sr1' and 'sr2' using the np.intersect1d() function. This will result in a new Series object 'sr22' containing only the values that are present in both Series objects 'sr1' and 'sr2'.
result = sr11[~sr11.isin(sr22)]: Finally this code creates a new Pandas Series object 'result' by selecting the elements from the original Series object 'sr11' that are not present in the Series object 'sr22'. This is done using boolean indexing and the .isin() method to check which elements in 'sr11' are present in 'sr22', 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 get the items of a given series not present in another given series.
Next: Write a Pandas program to compute the minimum, 25th percentile, median, 75th, and maximum of a given series.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/pandas/python-pandas-data-series-exercise-17.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics