ffill_bfill

Forward Fill and Backward Fill Demo


import pandas as pd
import numpy as np

df = pd.DataFrame({'year':[2018,2019, 2020, 2021], 'profit':[50,100,None,0]})
df
  year profit
0 2018 50.0
1 2019 100.0
2 2020 NaN
3 2021 0.0
df2 = df.copy()
df3 = df.copy()

Forward Fill (from row above)

### Forward fill, copy values 'forward'  from row above - (uses axis=0)
df=df.fillna(method='ffill', axis=0).fillna(0)
df
  year profit
0 2018 50.0
1 2019 100.0
2 2020 100.0
3 2021 0.0

Forward Fill (from previous (left) column )

### Forward fill, copy values 'forward' from previous column -  (uses axis=1)
df2=df2.fillna(method='ffill', axis=1).fillna(0)
df2
  year profit
0 2018.0 50.0
1 2019.0 100.0
2 2020.0 2020.0
3 2021.0 0.0

Backward Fill (copy value up from following row )

df4 = df3.fillna(method='bfill', axis=0).fillna(0)
df4
  year profit
0 2018 50.0
1 2019 100.0
2 2020 0.0
3 2021 0.0

Backward Fill (copy value across from following column )

df3
  year profit
0 2018 50.0
1 2019 100.0
2 2020 NaN
3 2021 0.0
df3.iloc[2,0]=None
df3.iloc[2,1]=1999
df3
  year profit
0 2018.0 50.0
1 2019.0 100.0
2 NaN 1999.0
3 2021.0 0.0
df3.fillna(method='bfill', axis=1).fillna(0)
  year profit
0 2018.0 50.0
1 2019.0 100.0
2 1999.0 1999.0
3 2021.0 0.0
Pandas

Previous article

Data Analysis With Pandas
Pandas

Next article

map & lambda