2024-04-20 15:25:09 发布
网友
为什么下面的代码返回False
False
>>> pd.Series([np.nan]) | pd.Series([True]) 0 False dtype: bool
比较您的案例(与显式dtype以强调推断的案例):
dtype
In[11]: pd.Series([np.nan], dtype=float) | pd.Series([True])
Out[11]: 0 False dtype: bool
有一个类似的(现在只有dtype是bool):
bool
In[12]: pd.Series([np.nan], dtype=bool) | pd.Series([True])
Out[12]: 0 True dtype: bool
你看到区别了吗
解释:
在第一种情况下(您的),np.nan在逻辑操作or(引擎盖下)中传播自身
np.nan
or
In[13]: np.nan or True Out[13]: nan
在布尔运算结果的上下文中,pandas将np.nan视为False
在第二种情况下,输出是明确的,因为第一个序列有一个布尔值(True,因为所有非零值都被视为True,包括np.nan,但在这种情况下这并不重要):
True
In[14]: pd.Series([np.nan], dtype=bool)
Out[14]: 0 True dtype: bool
当然{}给出了{}:
In[15]: True or True Out[15]: True
我认为这是因为np.nan有float的元类,我猜覆盖__bool__是非零的:
float
__bool__
np.nan.__bool__() == True
同样地:
>>>np.nan or None nan
熊猫的解决方案是:
pd.Series([np.nan]).fillna(False) | pd.Series([True])
编辑***
为清楚起见,在方法:_bool_method_SERIES的.../pandas/core/ops.py行1816中的pandas 0.24.1中有一个赋值:
_bool_method_SERIES
.../pandas/core/ops.py
1816
pandas 0.24.1
fill_bool = lambda x: x.fillna(False).astype(bool)
这就是你描述的行为的来源。也就是说,它被特意设计成np.nan被视为False值(无论何时执行或操作)
比较您的案例(与显式
dtype
以强调推断的案例):有一个类似的(现在只有
dtype
是bool
):你看到区别了吗
解释:
在第一种情况下(您的),
np.nan
在逻辑操作or
(引擎盖下)中传播自身在布尔运算结果的上下文中,pandas将
np.nan
视为False
在第二种情况下,输出是明确的,因为第一个序列有一个布尔值(
True
,因为所有非零值都被视为True
,包括np.nan
,但在这种情况下这并不重要):当然{}给出了{}:
我认为这是因为
np.nan
有float
的元类,我猜覆盖__bool__
是非零的:同样地:
熊猫的解决方案是:
编辑***
为清楚起见,在方法:
_bool_method_SERIES
的.../pandas/core/ops.py
行1816
中的pandas 0.24.1
中有一个赋值:这就是你描述的行为的来源。也就是说,它被特意设计成
np.nan
被视为False
值(无论何时执行或操作)相关问题 更多 >
编程相关推荐