Why do "Not a Number" values equal True when cast as boolean in Python/Numpy? Why do "Not a Number" values equal True when cast as boolean in Python/Numpy? numpy numpy

Why do "Not a Number" values equal True when cast as boolean in Python/Numpy?


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.


Python truth-value testing states that the following values are considered False:

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.

Numpy probably chose to stick with this behaviour and prevent NaN from evaluating to False in a boolean context. Note however that you can use numpy.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 have bool(np.nan) be False when bool(float('nan')) is True).

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.