Puzzle 11 | Phil? Nah!? |
| import numpy as np |
| import pandas as pd |
| |
| s = pd.Series([1, 2, np.nan, 4, 5]) |
| s.fillna(3) |
| print(s.sum()) |
Guess the Output | |
---|---|
Try to guess what the output is before moving to the next page. |
This code will print: 12.0
The pandas.Series.fillna documentation says the following:
Returns: Series or None
Object with missing values filled or None if inplace=True.
It’s always a good idea to not change (mutate) an object passed to a function. On the other hand, Pandas tries to be efficient and not copy data around a lot.
The design decision for fillna, both in pandas.Series and pandas.DataFrame, was not to change the original object and return a copy. But the user has an option to pass inplace=True, and then the original object is changed.
When a method changes an object, the common practice in Python is to return None. Other languages, such as JavaScript, prefer to return the object, allowing method chaining.
If you change line 5 to s.fillna(3, inplace=True), you’ll see 15.0 as the output.
fillna will work on anything that is considered a missing value: numpy.nan, pandas.NA, pandas.NaT, None …
Empty strings or collections are not considered missing values.
http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html
http://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html
3.139.79.59