How to do boolean algebra on missing values?
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream
--
Chapters
00:00 How To Do Boolean Algebra On Missing Values?
00:49 Answer 1 Score 0
01:05 Answer 2 Score 6
01:24 Accepted Answer Score 9
02:06 Thank you
--
Full question
https://stackoverflow.com/questions/1801...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #booleanexpression
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream
--
Chapters
00:00 How To Do Boolean Algebra On Missing Values?
00:49 Answer 1 Score 0
01:05 Answer 2 Score 6
01:24 Accepted Answer Score 9
02:06 Thank you
--
Full question
https://stackoverflow.com/questions/1801...
--
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