To replace NaNs by preceding or next values in a Python Pandas DataFrame we can use the fillna
method with the method
argument set to 'ffill'
.
For instance, we write
df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
df.fillna(method='ffill')
to call fillna
on dataframe df
with the method
argument set to 'ffill'
to fill NaNs with values before the next row.
We can also set method
to 'bfill '
to fill NaNs with values after the next row.