Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill NaN in pandas column in both direction

Tags:

python

pandas

In pandas.fillna,

method : {‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None
Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use NEXT valid observation to fill gap

How can I fill values both backward and forward? None of the options seem to do this

like image 258
user308827 Avatar asked Sep 06 '25 12:09

user308827


1 Answers

It seems very simple and there may be a quicker way, but simply chaining the two, like so

df.fillna(method='ffill').fillna(method='bfill')

This will fill forwards first and then backwards.

like image 111
RexFuzzle Avatar answered Sep 08 '25 03:09

RexFuzzle