Puzzle 18 Off with Their NaNs
Pandas Brain Teasers — by Miki Tebeka (26 / 34)
Published in
2 min readMar 23, 2022
👈 Not My Type | TOC | Holding out for a Hero 👉
import numpy as np
import pandas as pd
s = pd.Series([1, np.nan, 3])
print(s[~(s == np.nan)])
Guess the Output
IMPORTANT
Try to guess what the output is before moving to the next page.
This code will print:
0 1.0
1 NaN
2 3.0
dtype: float64
We covered some of the floating-point oddities in the puzzle Puzzle 12, Multiplying . NaN (or np.nan) is another oddity. The name NaN stands for not a number. It serves two purposes: illegal computation and missing values.
Here’s an example of a bad computation:
In [1]: np.float64(0)/np.float64(0)
RuntimeWarning: invalid value encountered in \
double_scalars np.float64(0)/np.float64(0)
Out[1]: nan
You see a warning but not an exception, and the return value is nan.