Why isn’t Pandas .fillna() filling values in DataFrame?

It has to do with the way you’re calling the fillna() function.

If you do inplace=True (see code below), they will be filled in place and overwrite your original data frame.

In [1]: paste
import pandas as pd
import numpy as np
from pandas import DataFrame
from numpy import nan

df = DataFrame([[1, nan], [nan, 4], [5, 6]])
## -- End pasted text --

In [2]: 

In [2]: df
Out[2]: 
    0   1
0   1 NaN
1 NaN   4
2   5   6

In [3]: df.fillna(0)
Out[3]: 
   0  1
0  1  0
1  0  4
2  5  6

In [4]: df2 = df

In [5]: df2.fillna(0)
Out[5]: 
   0  1
0  1  0
1  0  4
2  5  6

In [6]: df2  # note how this is unchanged.
Out[6]: 
    0   1
0   1 NaN
1 NaN   4
2   5   6

In [7]: df.fillna(0, inplace=True)  # this will replace the values.

In [8]: df
Out[8]: 
   0  1
0  1  0
1  0  4
2  5  6

In [9]: 

Leave a Comment