當嘗試對可能包含nan值(如numpy中定義)的數據求邏輯表達式時,我得到一些令人驚訝的結果。我想了解為什么會出現這種結果以及如何實施正確的方法。我不明白的是為什么這些表達式求值的價值:from numpy import nannan and True>>> True# this is wrong.. I would expect to evaluate to nanTrue and nan>>> nan# OKnan and False>>> False# OK regardless the value of the first element # the expression should evaluate to FalseFalse and nan>>> False#ok同樣適用于or:True or nan>>> True #OKnan or True>>> nan #wrong the expression is TrueFalse or nan>>> nan #OKnan or False>>> nan #OK如何實現(以有效的方式)正確的布爾函數,同時處理nan值?
2 回答

隔江千里
TA貢獻1906條經驗 獲得超10個贊
在評估包含的邏輯表達式時and
,我們必須評估and
運算符兩側都存在的表達式。而對于or
運算符,如果第一個表達式為True,則無需檢查第二個表達式的正確性
例如,在評估表達式時2>2 and 3==3
,首先我們應該檢查第一個表達式是否2>2
為True。如果第一個表達式為False,則由于AND
運算符而無需檢查第二個表達式,并且該表達式的結果將為FALSE,因為第一個表達式為FALSE。而如果表達式為2==2 AND 3==3
,則由于第一個表達式2==2
為True,則我們無需檢查第二個表達式的正確性,并且由于此處第二個表達式也為True,因此輸出為TRUE。
在中nan and True
,由于nan
是True且由于AND
運算符,所以python現在將評估第二個表達式并返回第二個表達式的值。因此,在這里您將獲得TRUE
輸出。將相同的邏輯應用于時True and nan
,您可以期望將其nan
作為輸出。
在OR
operator中,如果我們看第一個表達式就足夠了,因此“True or nan
將返回True
添加回答
舉報
0/150
提交
取消