Sort rows of a dataframe in descending order of NaN counts

前端 未结 4 2056
栀梦
栀梦 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 12:51

    You can add a column of the number of null values, sort by that column, then drop the column. It's up to you if you want to use .reset_index(drop=True) to reset the row count.

    df['null_count'] = df.isnull().sum(axis=1)
    df.sort_values('null_count', ascending=False).drop('null_count', axis=1)
    
    # returns
             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
    

提交回复
热议问题