Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a Pyton program to perform Boolean logical AND, OR, Ex-OR operations for a given series
Boolean logical operations on Pandas Series allow you to perform element-wise AND, OR, and XOR operations using bitwise operators &, |, and ^. These operations are useful for filtering data and creating conditional logic.
Creating a Boolean Series
First, let's create a Pandas Series with boolean values including np.nan ?
import pandas as pd
import numpy as np
# Create a boolean series with True, NaN, and False
series = pd.Series([True, np.nan, False], dtype="bool")
print("Original series:")
print(series)
Original series: 0 True 1 True 2 False dtype: bool
Boolean AND Operation
The AND operation using & returns True only when both operands are True ?
import pandas as pd
import numpy as np
series = pd.Series([True, np.nan, False], dtype="bool")
series_and = series & True
print("AND operation result:")
print(series_and)
AND operation result: 0 True 1 True 2 False dtype: bool
Boolean OR Operation
The OR operation using | returns True if at least one operand is True ?
import pandas as pd
import numpy as np
series = pd.Series([True, np.nan, False], dtype="bool")
series_or = series | True
print("OR operation result:")
print(series_or)
OR operation result: 0 True 1 True 2 True dtype: bool
Boolean XOR Operation
The XOR (exclusive OR) operation using ^ returns True when operands have different boolean values ?
import pandas as pd
import numpy as np
series = pd.Series([True, np.nan, False], dtype="bool")
series_xor = series ^ True
print("XOR operation result:")
print(series_xor)
XOR operation result: 0 False 1 False 2 True dtype: bool
Complete Example
Here's a complete program demonstrating all three boolean operations ?
import pandas as pd
import numpy as np
# Create boolean series
series = pd.Series([True, np.nan, False], dtype="bool")
# Perform boolean operations
series_and = series & True
series_or = series | True
series_xor = series ^ True
print("AND operation:")
print(series_and)
print("\nOR operation:")
print(series_or)
print("\nXOR operation:")
print(series_xor)
AND operation: 0 True 1 True 2 False dtype: bool OR operation: 0 True 1 True 2 True dtype: bool XOR operation: 0 False 1 False 2 True dtype: bool
Key Points
-
np.nanvalues are converted toTruewhen cast to boolean dtype - Use
&,|, and^for element-wise boolean operations - These operations work with scalars or other Series of the same length
Conclusion
Boolean operations on Pandas Series provide powerful tools for data filtering and conditional logic. Use & for AND, | for OR, and ^ for XOR operations on boolean data.
