为什么 python pandas 不使用三值逻辑?
Why python pandas does not use 3-valued logic?
我想知道为什么 python pandas / numpy 不使用 true、false 和 NA 实现三值逻辑(所谓的 Łukasiewicz 逻辑)(就像 R 那样)。我读过 (https://www.oreilly.com/learning/handling-missing-data) 这在某种程度上是由于 pandas 使用的基本数据类型比 R 多得多。但是,我并不完全清楚为什么在这种情况下不可避免地会出现这种带有缺失值的逻辑运算的奇怪行为。
示例。
import numpy as np
np.nan and False # so far so good, we have False
np.nan or False # again, good, we have nan
False and np.nan # False, good
False or np.nan # give nan, so again, it is correct
np.nan and True # weird, this gives True, while it should give nan
True and np.nan # nan, so it is correct, but switching order should not affect the result
np.nan or True # gives nan, which is not correct, should be True
True or np.nan # True so it is correct, again switching the arguments changes the result
所以这个例子表明在比较 np.nan
和 True
值时发生了一些非常奇怪的事情。那么这是怎么回事?
编辑。
感谢您的评论,现在我看到 np.nan
被认为是 "truthy" 值。那么谁能解释一下这到底是什么意思以及这种方法背后的基本原理是什么?
您错误地误判了 or
和 and
语句。
or
将检查 bool(value)
形式的第一个值是否为 True 如果它是 False
则它采用第二个值。
另一方面,and
检查两个值是否同时为 True
bool(value1)
和bool(value2)
这是 numpy 行为,至少部分继承自 python:
In [11]: bool(float('nan'))
Out[11]: True
In [12]: bool(np.NaN)
Out[12]: True
(NaN 是 "truthy"。)
我想知道为什么 python pandas / numpy 不使用 true、false 和 NA 实现三值逻辑(所谓的 Łukasiewicz 逻辑)(就像 R 那样)。我读过 (https://www.oreilly.com/learning/handling-missing-data) 这在某种程度上是由于 pandas 使用的基本数据类型比 R 多得多。但是,我并不完全清楚为什么在这种情况下不可避免地会出现这种带有缺失值的逻辑运算的奇怪行为。
示例。
import numpy as np
np.nan and False # so far so good, we have False
np.nan or False # again, good, we have nan
False and np.nan # False, good
False or np.nan # give nan, so again, it is correct
np.nan and True # weird, this gives True, while it should give nan
True and np.nan # nan, so it is correct, but switching order should not affect the result
np.nan or True # gives nan, which is not correct, should be True
True or np.nan # True so it is correct, again switching the arguments changes the result
所以这个例子表明在比较 np.nan
和 True
值时发生了一些非常奇怪的事情。那么这是怎么回事?
编辑。
感谢您的评论,现在我看到 np.nan
被认为是 "truthy" 值。那么谁能解释一下这到底是什么意思以及这种方法背后的基本原理是什么?
您错误地误判了 or
和 and
语句。
or
将检查 bool(value)
形式的第一个值是否为 True 如果它是 False
则它采用第二个值。
and
检查两个值是否同时为 True
bool(value1)
和bool(value2)
这是 numpy 行为,至少部分继承自 python:
In [11]: bool(float('nan'))
Out[11]: True
In [12]: bool(np.NaN)
Out[12]: True
(NaN 是 "truthy"。)