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.)
Python truth-value testing states that the following values are considered
False
:Numpy probably chose to stick with this behaviour and prevent NaN from evaluating to
False
in a boolean context. Note however that you can usenumpy.isnan
to test for NaN.0.0
is the only falsy float value because that's what the language designers decided would be most useful. Numpy simply follows along. (It would be weird to havebool(np.nan)
beFalse
whenbool(float('nan'))
isTrue
).I think it is probably because that's how things work with integers. Admittedly, integers have no NaN or inf types of values, but I suppose that special cases aren't special enough to break the rules.
This is in no way NumPy-specific, but is consistent with how Python treats NaNs:
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.
Numpy follows the python standard for truth testing here, any numeric type evaluates to
False
if and only if its numerical value is zero.Note that truth testing with
NaN
values can be unintuitive in other ways as well (e.g.,nan == nan
evaluates toFalse
).