'How to replace the missing values with average of ffill() and bfill() in pandas?

This is a sample dataframe and it containsNA:

    x    y    z      datetime
0   2    3    4    02-02-2019
1   NA   NA   NA   03-02-2019
2   3    5    7    04-02-2019
3   NA   NA   NA   05-02-2019
4   4    7    9    06-02-2019

Now, i want to fill these NA values and i can do this by using either ffill() or bfill(). But what if want to apply the average of the ffill() & bfill(). Then how can i do this?

The direct average df = (df.fill() + df.bfill()) / 2 didn't work because of datetime column.

The end dataframe should look like this:

      x    y     z      datetime
0     2    3     4    02-02-2019
1   2.5    4   5.5    03-02-2019
2     3    5     7    04-02-2019
3   3.5    6     8    05-02-2019
4     4    7     9    06-02-2019


Solution 1:[1]

Check with df.interpolate:

df.interpolate()

     x    y    z    datetime
0  2.0  3.0  4.0  02-02-2019
1  2.5  4.0  5.5  03-02-2019
2  3.0  5.0  7.0  04-02-2019
3  3.5  6.0  8.0  05-02-2019
4  4.0  7.0  9.0  06-02-2019

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 anky