ffill method for pandas in python

The ffill() method in pandas is used to forward fill (or propagate the last valid value forward) missing values in a DataFrame. This means that it fills the missing values with the last valid value that occurred before it.

To use the ffill() method on a pandas DataFrame, you can follow these steps:

  1. Import the pandas library:
main.py
import pandas as pd
20 chars
2 lines
  1. Create a DataFrame with missing values:
main.py
data = {'Column1': [1, 2, None, 4, None], 'Column2': [None, 5, None, None, 8]}
df = pd.DataFrame(data)
103 chars
3 lines
  1. Apply the ffill() method to fill the missing values:
main.py
df_filled = df.ffill()
23 chars
2 lines

The df_filled DataFrame will now have the missing values filled with the last valid values. In the example above, the missing value in Column1 will be filled with the value 2, while the missing values in Column2 will be filled with the value 5.

It's worth noting that the ffill() method propagates the last valid value forward, so if the first value in a column is missing, it will remain as missing.

Tags: pandas, fillna

related categories

gistlibby LogSnag