Puzzle 18 Off with Their NaNs

Pandas Brain Teasers — by Miki Tebeka (26 / 34)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Not My Type | TOC | Holding out for a Hero 👉

not_nan.py

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

images/hline.png

This code will print:

​ 0    1.0
​ 1 NaN
​ 2 3.0
​ dtype: float64
images/hline.png

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.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.