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:
JavaScript
x
7
1
import pandas as pd
2
import numpy as np
3
4
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']
5
df=pd.DataFrame(before_list)
6
df
7
The final dataframe should be the same as the output from the following:
JavaScript
1
4
1
after_list = ['Apples','Apples','Apples','Apples','Apples','Apples','Oranges','Oranges','Oranges','Oranges','Oranges','Bananna','Bananna','Bananna','Bananna']
2
df_after_update=pd.DataFrame(after_list)
3
df_after_update
4
Any help would be greatly appreciated, thanks in advance
Frank
Advertisement
Answer
You can use:
JavaScript
1
2
1
df.bfill(inplace=True)
2
Or you can use also as suggested by @G. Anderson :
JavaScript
1
2
1
df.fillna(method="bfill", inplace=True)
2