When casting a NumPy Not-a-Number value as a boolean, it becomes True, e.g. as follows.
>>> import numpy as np >>> bool(np.nan) True
This is the exact opposite to what I would intuitively expect. Is there a sound principle underlying this behaviour?
(I suspect there might be as the same behaviour seems to occur in Octave.)
There are two Boolean. values: True and False. Values in Python can be compared using comparison operations, and Boolean logic can be formulated with the use of logic operations.
Operator precedence... the == binds tighter than in , so [1,0] == True gets evaluated first, then the result of that gets fed to 1 in other_result . I've removed the Python-2.7 tag, since Python 3.2 behaves the same way.
In Python, the two Boolean values are True and False (the capitalization must be exactly as shown), and the Python type is bool. In the first statement, the two operands evaluate to equal values, so the expression evaluates to True; in the second statement, 5 is not equal to 6, so we get False.
Because True is equal to 1 and False is equal to 0 , adding Booleans together is a quick way to count the number of True values.
This is in no way NumPy-specific, but is consistent with how Python treats NaNs:
In [1]: bool(float('nan')) Out[1]: True
The rules are spelled out in the documentation.
I think it could be reasonably argued that the truth value of NaN should be False. However, this is not how the language works right now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With