I have a dataframe.
import pandas as pd
df = pd.DataFrame({'menu1': [5, 5, 5, 5, 5, None, None],
'menu2': [4, 4, None, 4, None, None, None],
'menu3': [None, None, 9, 9, None, None, None]
})
df
For each column, I would like to find the last positive value and replace NAN with that value.
df = pd.DataFrame({'menu1': [5, 5, 5, 5, 5, 5, 5],
'menu2': [4, 4, None, 4, 4, 4, 4],
'menu3': [None, None, 9, 9, 9, 9, 9]
})
df
>Solution :
Using interpolation method pandas.DataFrame.interpolate with specific options:
df.interpolate(limit_direction='forward', limit_area='outside')
limit_direction='forward'– tells in what direction NaNs will be filled inlimit_area='outside'– tells to only fill NaNs outside valid values (means thatNaNshould not be surrounded by valid values)
menu1 menu2 menu3
0 5.0 4.0 NaN
1 5.0 4.0 NaN
2 5.0 NaN 9.0
3 5.0 4.0 9.0
4 5.0 4.0 9.0
5 5.0 4.0 9.0
6 5.0 4.0 9.0