Search code examples
pythonpandasfillna

Pandas fillna row wise?


It'a simple example.

d=pd.DataFrame({'x':[1,None,None,3,4],'y':[3,2,3,None,7],'z':[None,None,None,None,None]})
d['t']=d.mean(axis=1)

Out[96]: 
     x    y     z    t
0  1.0  3.0  None  2.0
1  NaN  2.0  None  2.0
2  NaN  3.0  None  3.0
3  3.0  NaN  None  3.0
4  4.0  7.0  None  5.5

I want to fill NA with the mean of the row.The mean of every row I have added
as t.The result I want is:

x y z 
1 3 2
2 2 2
3 3 3
3 3 3
4 7 5.5

Solution

  • You can do it like this:

    d.T.fillna(d.T.mean(axis=0), axis=0).T
    

    You have to transpose the dataframe because this:

    d.fillna(d.mean(axis=1), axis=1)
    

    is not implemented (NotImplementedError)