使用inf和NaN对pandas数据帧进行排序

时间:2017-03-28 18:04:02

标签: sorting pandas dataframe

我有一个pandas数据框,我想按列的降序排序。

this.authenticationservice.authentication(this.UserName, this.Password)
  .subscribe(
    response => {
      console.log(response);
      if (response.status != null) {
        switch (response.status) {
          case 'Success':
            this.response = response.message;
            console.log(this.response);
            break;
          case 'Failure':
            this.response = response.message;
            this.loginStat = true;
            break;
        }
      }
    })

我希望按降序排序,并将Name count AAAA -1.1 BBBB 0 CCCC -10 DDDD inf EEEE 3 FFFF NaN GGGG 30 inf行移到最后。 NaNdf.sort('count',ascending = False,na_position="last")推到最后。如何处理NaN

2 个答案:

答案 0 :(得分:4)

您可以将inf值视为null:

with pd.option_context('mode.use_inf_as_null', True):
    df = df.sort_values('count', ascending=False, na_position='last')


df
Out: 
   Name      count
6  GGGG  30.000000
4  EEEE   3.000000
1  BBBB   0.000000
0  AAAA  -1.100000
2  CCCC -10.000000
3  DDDD        inf
5  FFFF        NaN 

答案 1 :(得分:2)

可能的解决方案之一:

In [33]: df.assign(x=df['count'].replace(np.inf, np.nan)) \
           .sort_values('x', ascending=False) \
           .drop('x', 1)
Out[33]:
   Name      count
6  GGGG  30.000000
4  EEEE   3.000000
1  BBBB   0.000000
0  AAAA  -1.100000
2  CCCC -10.000000
3  DDDD        inf
5  FFFF        NaN