Python Pandas Series.backfill() Method

If we want to replace missing values or null values with others, we can choose the backfill method. In this tutorial, we will learn the python pandas Series.backfill() method which fills the null or missing values backward. It returns Series with the missing values filled or None if the inplace is True.

The below shows the syntax of the Series.backfill() method.

Syntax

Series.backfill(axis=None, inplace=False, limit=None, downcast=None)

Example: Fill missing values using the Series.backfill() method

Let's fill in the missing values present in the Series using the Series.backfill() method. This method backward fills the null or missing values present in the Series. See the below example.

#importing pandas as pd
import pandas as pd
#creating Series
series=pd.Series([None,5,None,10])
print("-----------The Series is---------")
print(series)
print("---------------------------------")
print(series.backfill())


-----------The Series is---------
0 NaN
1 5.0
2 NaN
3 10.0
dtype: float64
---------------------------------
0 5.0
1 5.0
2 10.0
3 10.0
dtype: float64

Example: Set limit in the Series.backfill() method

Here, in this example, we set the limit parameter to some integer. Using this parameter we can define a limit to the Series.backfill() method to fill the number of consecutive missing values. See the below example.

In the below example, the Series consists of three consecutive missing values and the Series.backfill() method fills only two missing values as the limit is set to 2.

#importing pandas as pd
import pandas as pd
#creating Series
series=pd.Series([None,None,None,5])
print("-----------The Series is---------")
print(series)
print("---------------------------------")
print(series.backfill(limit=2))


-----------The Series is---------
0 NaN
1 NaN
2 NaN
3 5.0
dtype: float64
---------------------------------
0 NaN
1 5.0
2 5.0
3 5.0
dtype: float64

Example: Set inplace=True in the Series.backfill() method

Here, in this example, we have set inplace=True in the Series.backfill() method. As this parameter is True, the Series.backfill() method fills the missing values without creating the new object and it returns None. See the below example.

#importing pandas as pd
import pandas as pd
#creating Series
series=pd.Series([None,5,None,5])
print("-----------The Series is---------")
print(series)
print("---------------------------------")
print(series.backfill(inplace=True))


-----------The Series is---------
0 NaN
1 5.0
2 NaN
3 5.0
dtype: float64
---------------------------------
None
0 5.0
1 5.0
2 5.0
3 5.0
dtype: float64

Conclusion

In this tutorial, we learned the Python pandas Series.backfill() method. We learned the syntax and parameters of the method and we applied this method on Series that consisting of None values and understood Series.backfill() method.