How to backward fill in Python

1 min readDataFrameData ManipulationDataPandas
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

The Pandas library will give you the tools to backward fill the NaN values.

What is backward fill ?

Backward fill will give the next available value for every NaN.

This useful when you are working with timeseries and need to take the next available values.

An example dataframe with NaN values

Using fillna

The .fillna() method will replace all NaN or null values contained in a pandas.Series ou pandas.DataFrame.

As we could have seen in the fillna article we can specify the method we want to use.

Here for our example we are going to use the forward fill method or "bfill"

Using bfill on a Serie

# Here we apply the ffill method on a our column called my_column
df["my_column"] = df["my_column"].fillna(method="bfill")
The bfill method used to fill the current NaN value with the next available value

Using bfill on a DataFrame

# Here we apply the ffill method on a our dataframe
df = df.fillna(method="bfill")
The bfill method used to fill the current NaN value with the next available value

Here you are, you know how to replace your NaN by the next available value, or backward fill.

If you want to learn more about forward fill, you can check the links below

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.