为什么pd系列([np.nan])| pd系列([True])的计算结果为False?

2024-04-20 15:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么下面的代码返回False

>>> pd.Series([np.nan]) | pd.Series([True])
0    False
dtype: bool

Tags: 代码falsetruenpnanseriespdbool
2条回答

比较您的案例(与显式dtype以强调推断的案例):

In[11]: pd.Series([np.nan], dtype=float) | pd.Series([True])
Out[11]: 
0    False
dtype: bool

有一个类似的(现在只有dtypebool):

In[12]: pd.Series([np.nan], dtype=bool) | pd.Series([True])
Out[12]: 
0    True
dtype: bool

你看到区别了吗


解释:

  1. 在第一种情况下(您的),np.nan在逻辑操作or(引擎盖下)中传播自身

    In[13]: np.nan or True
    Out[13]: nan
    

    在布尔运算结果的上下文中,pandas将np.nan视为False

  2. 在第二种情况下,输出是明确的,因为第一个序列有一个布尔值(True,因为所有非零值都被视为True,包括np.nan,但在这种情况下这并不重要):

    In[14]: pd.Series([np.nan], dtype=bool)
    
    Out[14]: 
    0    True
    dtype: bool
    

    当然{}给出了{}:

    In[15]: True or True
    Out[15]: True
    

我认为这是因为np.nanfloat的元类,我猜覆盖__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.py1816中的pandas 0.24.1中有一个赋值:

    fill_bool = lambda x: x.fillna(False).astype(bool)

这就是你描述的行为的来源。也就是说,它被特意设计成np.nan被视为False值(无论何时执行操作)

相关问题 更多 >