可為 Null 的布林資料類型#
注意
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
。例如,真 | NA
是 真
,因為 真 | 真
和 真 | 假
都是 真
。在這種情況下,我們實際上不需要考慮 NA
的值。
另一方面,真 & NA
是 NA
。結果取決於 NA
實際上是 真
還是 假
,因為 真 & 真
是 真
,但 真 & 假
是 假
,所以我們無法確定輸出。
這與 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