Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

math

numpy

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

like image 384
rroowwllaanndd Avatar asked Mar 28 '13 15:03

rroowwllaanndd


People also ask

Is true a boolean in Python?

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.

Does 1 == true evaluate true or false in Python?

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.

Why is true and false false in Python?

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.

Does Python interpret 1 as true?

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.


1 Answers

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.

like image 70
NPE Avatar answered Oct 05 '22 03:10

NPE