可空布尔数据类型#
备注
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
如果你创建一列 NA 值(例如为了稍后填充它们)使用 df['new_col'] = pd.NA,新的列中的 dtype 将被设置为 object。这个列的性能将比使用适当类型时差。最好使用 df['new_col'] = pd.Series(pd.NA, dtype="boolean")``(或其他支持 ``NA 的 dtype)。
In [5]: df = pd.DataFrame()
In [6]: df['objects'] = pd.NA
In [7]: df.dtypes
Out[7]:
objects object
dtype: object
克莱尼逻辑运算#
arrays.BooleanArray 实现了 `Kleene Logic`_(有时称为三值逻辑),用于逻辑操作,如 ``&``(与)、``|``(或)和 ``^``(异或)。
此表展示了每种组合的结果。这些操作是对称的,因此翻转左侧和右侧不会影响结果。
表达式 |
结果 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
当操作中存在 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 视为 在输出中总是为假。
在 或
In [8]: pd.Series([True, False, np.nan], dtype="object") | True
Out[8]:
0 True
1 True
2 False
dtype: bool
In [9]: pd.Series([True, False, np.nan], dtype="boolean") | True
Out[9]:
0 True
1 True
2 True
dtype: boolean
在 和
In [10]: pd.Series([True, False, np.nan], dtype="object") & True
Out[10]:
0 True
1 False
2 False
dtype: bool
In [11]: pd.Series([True, False, np.nan], dtype="boolean") & True
Out[11]:
0 True
1 False
2 <NA>
dtype: boolean