Categories
Python Answers

How to replace NaNs by preceding or next values in a Python Pandas DataFrame?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *