编写一个Pyton程序以对给定系列执行布尔逻辑AND,OR,Ex-OR操作

假设您有一个系列以及布尔运算的结果,

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

解决方案

为了解决这个问题,我们将遵循以下方法。

  • 定义系列

  • 用布尔值和nan值创建一个序列

  • 对下面定义的系列中的每个元素按位与运算执行布尔True,

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

  • 对按位执行布尔True | 对以下定义的系列中的每个元素进行操作,

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

  • 对下面定义的系列中的每个元素执行按位^运算的布尔True,

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

例子

让我们看到完整的实现以更好地理解-

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)

输出

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

猜你喜欢