Sort rows of a dataframe in descending order of NaN counts

前端 未结 4 2075
栀梦
栀梦 2021-01-13 12:41

I\'m trying to sort the following Pandas DataFrame:

         RHS  age  height  shoe_size  weight
0     weight  NaN     0.0        0.0     1.0
1  shoe_size  N         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-13 13:06

    Here's a one-liner that will do it:

    df.assign(Count_NA = lambda x: x.isnull().sum(axis=1)).sort_values('Count_NA', ascending=False).drop('Count_NA', axis=1)
    #          RHS  age  height  shoe_size  weight
    # 1  shoe_size  NaN     0.0        1.0     NaN
    # 0     weight  NaN     0.0        0.0     1.0
    # 2  shoe_size  3.0     0.0        0.0     NaN
    # 3     weight  3.0     0.0        0.0     1.0
    # 4        age  3.0     0.0        0.0     1.0
    

    This works by assigning a temporary column ("Count_NA") to count the NAs in each row, sorting on that column, and then dropping it, all in the same expression.

提交回复
热议问题