Search code examples
pythonpandasdataframefillna

Pandas fillna() not working on DataFrame slices


Pandas fillna is not working on DataFrame slices, here is an example

df = pd.DataFrame([[np.nan, 2, np.nan, 0],
                [3, 4, np.nan, 1],
                [np.nan, np.nan, np.nan, 5],
                [np.nan, 3, np.nan, 4]],
                columns=list('ABCD'))
df[["A", 'B']].fillna(0, inplace=True)

the DataFrame doesn't change

    A   B   C   D
0   NaN 2.0 NaN 0
1   3.0 4.0 NaN 1
2   NaN NaN NaN 5
3   NaN 3.0 NaN 4

in contrast

df["A"].fillna(0, inplace=True)

and

df.fillna(0, inplace=True)

work fine.

Is this a bug or does it work as intended? Thx in advance.

P.S. this question asks how to use fillna on a slice, as for my question, it concerns why the above does'n work. The answer is in @heena-bawa answers comment section.


Solution

  • You can use:

    df[['A','B']] = df[['A','B']].fillna(0)
    
         A    B   C  D
    0  0.0  2.0 NaN  0
    1  3.0  4.0 NaN  1
    2  0.0  0.0 NaN  5
    3  0.0  3.0 NaN  4