fillna() with Pandas Series

Let's find out how to use the fillna() function.

We'll cover the following

Try it yourself

Try executing the code below to see the result.

Press + to interact
import numpy as np
import pandas as pd
s = pd.Series([1, 2, np.nan, 4, 5])
s.fillna(3)
print(s.sum())

Explanation

The pandas.Series.fillna documentation says, that it returns the following:

"Returns: Series or None

Object with missing values filled or None if inplace = True."

It’s never a good idea to change or 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, wasn’t to change the original object and return a copy. But, the user has an option to pass inplace = True, which changes the original object.

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 we change line 5 to s.fillna(3, inplace = True), we’ll see 15.0 as the output. The fillna will work on anything that is considered a missing value like: numpy.nan, pandas.NA, pandas.NaT, and None. Empty strings or collections aren’t considered missing values.

Solution

Press + to interact
import numpy as np
import pandas as pd
s = pd.Series([1, 2, np.nan, 4, 5])
s.fillna(3, inplace = True)
print(s.sum())

Get hands-on with 1300+ tech skills courses.