Shift NaNs to the end of their respective rows

后端 未结 2 902
情深已故
情深已故 2020-11-29 10:35

I have a DataFrame like :

     0    1    2
0  0.0  1.0  2.0
1  NaN  1.0  2.0
2  NaN  NaN  2.0

What I want to get is

         


        
2条回答
  •  春和景丽
    2020-11-29 11:29

    Your best easiest option is to use sorted on df.apply/df.transform and sort by nullity.

    df = df.apply(lambda x: sorted(x, key=pd.isnull), 1)
    df
         0    1    2
    0  0.0  1.0  2.0
    1  1.0  2.0  NaN
    2  2.0  NaN  NaN
    

    You may also pass np.isnan to the key argument.

提交回复
热议问题