Skip to content
Advertisement

Replacing a null value with the next null value in dataframe column [closed]

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

Advertisement

Answer

You can use:

df.bfill(inplace=True)

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

df.fillna(method="bfill", inplace=True)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement