Write a Pyton program to perform Boolean logical AND, OR, Ex-OR operations for a given series



Assume you have a series and the result for Boolean operations,

And operation is:
0    True
1    True
2    False
dtype: bool

Or operation is:
0    True
1    True
2    True
dtype: bool

Xor operation is:
0    False
1    False
2    True
dtype: bool

Solution

To solve this, we will follow the below approach.

  • Define a Series

  • Create a series with boolean and nan values

  • Perform boolean True against bitwise & operation to each element in the series defined below,

series_and = pd.Series([True, np.nan, False], dtype="bool") & True
  • Perform boolean True against bitwise | operation to each element in the series defined below,

series_or = pd.Series([True, np.nan, False], dtype="bool") | True
  • Perform boolean True against bitwise ^ operation to each element in the series defined below,

series_xor = pd.Series([True, np.nan, False], dtype="bool") ^ True

Example

Let us see the complete implementation to get a better understanding −

import pandas as pd
import numpy as np
series_and = pd.Series([True, np.nan, False], dtype="bool") & True
print("And operation is: \n",series_and)
series_or = pd.Series([True, np.nan, False], dtype="bool") | True
print("Or operation is: \n", series_or)
series_xor = pd.Series([True, np.nan, False], dtype="bool") ^ True
print("Xor operation is: \n", series_xor)

Output

And operation is:
0    True
1    True
2    False
dtype: bool

Or operation is:
0    True
1    True
2    True
dtype: bool

Xor operation is:
0    False
1    False
2    True
dtype: bool

Advertisements