pythonbeginner

Pandas Forward Fill & Backward Fill

Propagate non-null values forward and backward to fill gaps in time-series or sparse data.

python
import pandas as pd
import numpy as np

df = pd.DataFrame({'date': pd.date_range('2024-01-01', periods=10),'price': [100, np.nan, np.nan, 103, np.nan, 105, np.nan, np.nan, np.nan, 109],'volume':[500, np.nan, 600, np.nan, 700, np.nan, 800, np.nan, 900, np.nan]})

df['price_ffill']  = df['price'].ffill()
df['price_bfill']  = df['price'].bfill()
df['volume_interpolated'] = df['volume'].interpolate(method='linear')

print(df)

Use Cases

  • gap filling
  • time-series imputation
  • sensor data

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.