Pandas Data Series: Check inequality over the index axis of a given dataframe and a given series
Pandas: Data Series Exercise-40 with Solution
Write a Pandas program to check inequality over the index axis of a given dataframe and a given series.
Sample Solution :
Python Code :
import pandas as pd
df_data = pd.DataFrame({'W':[68,75,86,80,None],'X':[78,75,None,80,86], 'Y':[84,94,89,86,86],'Z':[86,97,96,72,83]});
sr_data = pd.Series([68, 75, 86, 80, None])
print("Original DataFrame:")
print(df_data)
print("\nOriginal Series:")
print(sr_data)
print("\nCheck for inequality of the said series & dataframe:")
print(df_data.ne(sr_data, axis = 0))
Sample Output:
Original DataFrame: W X Y Z 0 68.0 78.0 84 86 1 75.0 75.0 94 97 2 86.0 NaN 89 96 3 80.0 80.0 86 72 4 NaN 86.0 86 83 Original Series: 0 68.0 1 75.0 2 86.0 3 80.0 4 NaN dtype: float64 Check for inequality of the said series & dataframe: W X Y Z 0 False True True True 1 False False True True 2 False True True True 3 False False True True 4 True True True True
Explanation:
df_data = pd.DataFrame({'W':[68,75,86,80,None],'X':[78,75,None,80,86], 'Y':[84,94,89,86,86],'Z':[86,97,96,72,83]}); sr_data = pd.Series([68, 75, 86, 80, None])
The above code creates a Pandas DataFrame object 'df_data' containing four columns ('W', 'X', 'Y', 'Z') and five rows, and a Pandas Series object 'sr_data' containing the same values as the 'W' column of the DataFrame.
df_data.ne(sr_data, axis = 0) : Here .ne() method is used to compare the dataframe df_data with the series sr_data. ne stands for "not equal". The axis=0 parameter tells pandas to compare the rows of the dataframe and the series. The resulting dataframe will have the same shape as df_data and will contain boolean values indicating whether the corresponding elements in df_data are not equal to the values in sr_data.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Pandas program to find the index of the first occurrence of the smallest and largest value of a given series.
Next: Python Pandas Data Series, DataFrame Exercises Home.
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://w3resource.com/python-exercises/pandas/python-pandas-data-series-exercise-40.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics