可空布尔数据类型#
注意
BooleanArray 目前处于实验阶段。其 API 或实现可能会在不发出警告的情况下发生变化。
使用 NA 值进行索引#
pandas 允许使用布尔数组中的 NA 值进行索引,这些值被视为 False。
In [1]: s = pd.Series([1, 2, 3])
In [2]: mask = pd.array([True, False, pd.NA], dtype="boolean")
In [3]: s[mask]
Out[3]:
0 1
dtype: int64
如果你希望保留 NA 值,你可以使用 fillna(True) 手动填充它们。
In [4]: s[mask.fillna(True)]
Out[4]:
0 1
2 3
dtype: int64
克莱尼逻辑运算#
arrays.BooleanArray 为逻辑运算(如 & (与), | (或) 和 ^ (异或))实现了克莱尼逻辑(有时称为三值逻辑)。
此表展示了所有组合的结果。这些操作是对称的,因此翻转左侧和右侧不会影响结果。
表达式 |
结果 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
当操作中存在 NA 时,只有当结果不能仅根据另一个输入确定时,输出值才为 NA。例如,True | NA 为 True,因为 True | True 和 True | False 都为 True。在这种情况下,我们实际上不需要考虑 NA 的值。
另一方面,True & NA 为 NA。结果取决于 NA 究竟是 True 还是 False,因为 True & True 为 True,而 True & False 为 False,所以我们无法确定输出。
这与 np.nan 在逻辑运算中的行为不同。pandas 将 np.nan 视为 输出中始终为假。
在 or 中
In [5]: pd.Series([True, False, np.nan], dtype="object") | True
Out[5]:
0 True
1 True
2 False
dtype: bool
In [6]: pd.Series([True, False, np.nan], dtype="boolean") | True
Out[6]:
0 True
1 True
2 True
dtype: boolean
在 and 中
In [7]: pd.Series([True, False, np.nan], dtype="object") & True
Out[7]:
0 True
1 False
2 False
dtype: bool
In [8]: pd.Series([True, False, np.nan], dtype="boolean") & True
Out[8]:
0 True
1 False
2 <NA>
dtype: boolean