The Python Oracle

How to do boolean algebra on missing values?

This video explains
How to do boolean algebra on missing values?

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Underwater World

--

Chapters
00:00 Question
01:04 Accepted answer (Score 9)
02:10 Answer 2 (Score 6)
02:32 Answer 3 (Score 0)
02:53 Thank you

--

Full question
https://stackoverflow.com/questions/1801...

Question links:
[http://stat.ethz.ch/R-manual/R-devel/lib...]: http://stat.ethz.ch/R-manual/R-devel/lib...

Answer 2 links:
[http://docs.python.org/2/reference/datam...]: http://docs.python.org/2/reference/datam...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #booleanexpression

#avk47



ACCEPTED ANSWER

Score 9


As other have said, you can define your own class.

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_()

Use:

>>> 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
>>>



ANSWER 2

Score 6


You can do this by creating a class and overriding the boolean operation methods.

>>> 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



ANSWER 3

Score 0


You can define a custom class (singleton?) and define custom __and__ (and whatever other you neeed) function. See this:

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