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

images/aside-icons/important.png

Try to guess what the output is before moving to the next page.

images/hline.png

This code will print: 12.0

images/hline.png

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.

Further Reading

pandas.Series.fillna Documentation

http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.fillna.html

Working with Missing Data in the Pandas Documentation

http://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html

Method Chaining on Wikipedia

http://en.wikipedia.org/wiki/Method_chaining

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.79.59