为什么以下代码会返回
False
?>>> pd.Series([np.nan]) | pd.Series([True])
0 False
dtype: bool
我认为这是因为np.nan
具有float
的元类,并且我猜测覆盖了__bool__
以使其非零:
np.nan.__bool__() == True
>>>np.nan or None
nan
在pandas中的解决方案是:
pd.Series([np.nan]).fillna(False) | pd.Series([True])
为了更清楚,pandas 0.24.1
版本中,在方法_bool_method_SERIES
的1816
行,位于.../pandas/core/ops.py
文件中,有一个赋值语句:
fill_bool = lambda x: x.fillna(False).astype(bool)
这就是你所描述的行为的来源。也就是说,它被特意设计成在进行或运算时像False
值一样对待np.nan
。
np.nan
被视为False
值(每当进行或操作时)”- 不,np.nan
并不被视为不同的东西,请尝试np.nan or True
,您会发现结果是np.nan
。 - MarianD__or__
操作期间,pandas
会用False
填充np.nan
- 希望这有所帮助。 - Reubennp.nan
填充False
",那么为什么False or True
会得到False
(如OP示例中所示)?将您的案例(使用显式的dtype
来强调推断出的类型)进行比较:
In[11]: pd.Series([np.nan], dtype=float) | pd.Series([True])
Out[11]:
0 False
dtype: bool
和类似的另一个(只是 dtype
现在是 bool
):
In[12]: pd.Series([np.nan], dtype=bool) | pd.Series([True])
Out[12]:
0 True
dtype: bool
你看到区别了吗?
解释:
In the first case (yours), np.nan
propagates itself in the logical operation or
(under the hood)
In[13]: np.nan or True
Out[13]: nan
and pandas treated np.nan
as False
in the context of an boolean operation result.
In the second case the output is unambiguous, as the first series has a boolean value (True
, as all non-zero values are considered True
, including np.nan
, but it doesn't matter in this case):
In[14]: pd.Series([np.nan], dtype=bool)
Out[14]:
0 True
dtype: bool
and True or True
gives True
, of course:
In[15]: True or True
Out[15]: True
True
。应该在他们的 Github 上开一个 issue。 - rafaelcnp.nan or True
的计算结果为nan
,基本上,nan
将在您的操作中传播。真正奇怪的是,bool(np.nan)
实际上会返回True
,更加奇怪的是,pd.Series([np.nan],dtype=np.bool)
会给你一个只有一个True
的系列。 - juanpa.arrivillagapd.NA
(而不是np.nan
)不会传播。 - rafaelc