- User Guide
- Nullable...
Nullable Boolean data type#
Note
BooleanArray is currently experimental. Its API or implementation maychange without warning.
Indexing with NA values#
pandas allows indexing withNA
values in a boolean array, which are treated asFalse
.
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 1dtype: int64
If you would prefer to keep theNA
values you can manually fill them withfillna(True)
.
In [4]:s[mask.fillna(True)]Out[4]:0 12 3dtype: int64
Kleene logical operations#
arrays.BooleanArray
implementsKleene Logic (sometimes called three-value logic) forlogical operations like&
(and),|
(or) and^
(exclusive-or).
This table demonstrates the results for every combination. These operations are symmetrical,so flipping the left- and right-hand side makes no difference in the result.
Expression | Result |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
When anNA
is present in an operation, the output value isNA
only ifthe result cannot be determined solely based on the other input. For example,True|NA
isTrue
, because bothTrue|True
andTrue|False
areTrue
. In that case, we don’t actually need to consider the valueof theNA
.
On the other hand,True&NA
isNA
. The result depends on whethertheNA
really isTrue
orFalse
, sinceTrue&True
isTrue
,butTrue&False
isFalse
, so we can’t determine the output.
This differs from hownp.nan
behaves in logical operations. pandas treatednp.nan
isalways false in the output.
Inor
In [5]:pd.Series([True,False,np.nan],dtype="object")|TrueOut[5]:0 True1 True2 Falsedtype: boolIn [6]:pd.Series([True,False,np.nan],dtype="boolean")|TrueOut[6]:0 True1 True2 Truedtype: boolean
Inand
In [7]:pd.Series([True,False,np.nan],dtype="object")&TrueOut[7]:0 True1 False2 Falsedtype: boolIn [8]:pd.Series([True,False,np.nan],dtype="boolean")&TrueOut[8]:0 True1 False2 <NA>dtype: boolean