Home > Software design >  Replacing a null value with the next null value in dataframe column
Replacing a null value with the next null value in dataframe column

Time:02-26

I am looking to replace all null and subsequent nulls in a pandas dataframe with the next non null value that is in the column:

import pandas as pd
import numpy as np

before_list = ['Apples',np.NAN,np.NAN,np.NAN,np.NAN,'Apples','Oranges',np.NAN,np.NAN,np.NAN,'Oranges','Bananna',np.NAN,np.NAN,'Bananna']
df=pd.DataFrame(before_list)
df

The final dataframe should be the same as the output from the following:

after_list = ['Apples','Apples','Apples','Apples','Apples','Apples','Oranges','Oranges','Oranges','Oranges','Oranges','Bananna','Bananna','Bananna','Bananna']
df_after_update=pd.DataFrame(after_list)
df_after_update

Any help would be greatly appreciated, thanks in advance

Frank

CodePudding user response:

You can use:

df.bfill(inplace=True)

Or you can use also as suggested by @G. Anderson :

df.fillna(method="bfill", inplace=True)
  • Related