14

我想复制布尔NA值,因为它们在 R 中的行为:

NA 是一个有效的逻辑对象。如果 x 或 y 的分量为 NA,则如果结果不明确,则结果将为 NA。换句话说,NA & TRUE 的计算结果为 NA,但 NA & FALSE 的计算结果为 FALSE。 http://stat.ethz.ch/R-manual/R-devel/library/base/html/Logic.html

我已经看到None推荐用于缺失值,但 Python在评估布尔表达式时转换None为,并计算为. 结果当然应该是,因为给定缺失值无法得出任何结论。FalseNone or FalseFalseNone

我如何在 Python 中实现这一点?

编辑接受的答案使用按位布尔运算符正确计算,但要使用逻辑运算符 和 实现相同的行为notor似乎and需要更改 Python 编程语言。

4

3 回答 3

9

正如其他人所说,您可以定义自己的类。

class NA_(object):
    instance = None # Singleton (so `val is NA` will work)
    def __new__(self):
        if NA_.instance is None:
            NA_.instance = super(NA_, self).__new__(self)
        return NA_.instance
    def __str__(self): return "NA"
    def __repr__(self): return "NA_()"
    def __and__(self, other):
        if self is other or other:
            return self
        else:
            return other
    __rand__ = __and__
    def __or__(self, other):
        if self is other or other:
            return other
        else:
            return self
    __ror__ = __or__
    def __xor__(self, other):
        return self
    __rxor__ = __xor__
    def __eq__(self, other):
        return self is other
    __req__ = __eq__
    def __nonzero__(self):
        raise TypeError("bool(NA) is undefined.")
NA = NA_()

利用:

>>> print NA & NA
NA
>>> print NA & True
NA
>>> print NA & False
False
>>> print NA | True
True
>>> print NA | False
NA
>>> print NA | NA
NA
>>> print NA ^ True
NA
>>> print NA ^ NA
NA
>>> if NA: print 3
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 28, in __nonzero__
TypeError: bool(NA) is undefined.
>>> if NA & False: print 3
...
>>>
>>> if NA | True: print 3
...
3
>>>
于 2013-08-02T17:02:25.010 回答
6

您可以通过创建一个类并覆盖布尔操作方法来做到这一点。

>>> class NA_type(object):
        def __and__(self,other):
                if other == True:
                        return self
                else:
                        return False
        def __str__(self):
                return 'NA'


>>> 
>>> NA = NA_type()
>>> print NA & True
NA
>>> print NA & False
False
于 2013-08-02T14:31:25.370 回答
0

您可以定义自定义类(单例?)并定义自定义__and__(以及您需要的任何其他功能)。看到这个:

http://docs.python.org/2/reference/datamodel.html#emulating-numeric-types

于 2013-08-02T14:31:13.120 回答