Use-Isna¶
Sourcery rule id: use-isna
¶
Description¶
Use .isna()
or .isnull()
instead of == np.nan
for detecting missing values.
Before¶
import numpy as np
df['column'] == np.nan
After¶
import numpy as np
df['column'].isna()
Explanation¶
Use .isna()
or .isnull()
for detecting missing values.
A comparison like df['column'] == np.nan
doesn't produce the expected results when checking for missing or NaN (Not a Number) values. This is due to the peculiar nature of NaN: It is not considered equal to any value, even itself.
data = {
'A': [1, 2, np.nan, 4],
'B': [9, 10, 11, 12]
}
df = pd.DataFrame(data)
print(df['A'] == np.nan)
The output:
0 False 1 False 2 False 3 False Name: A, dtype: bool
print(df['A'].isna())
The output:
0 False 1 False 2 True 3 False Name: A, dtype: bool
See also Pandas Docs / Missing Data