Sorting pandas dataframe with inf and NaN

I have a pandas dataframe that I would like to sort in descending column order.

Name   count
AAAA    -1.1
BBBB     0
CCCC    -10
DDDD     inf
EEEE     3
FFFF     NaN
GGGG     30

      

I want to sort by, in descending order, and move the line inf

and NaN

up to the end. df.sort('count',ascending = False,na_position="last")

pushes NaN

to the end. How to deal with inf

?

+3


source to share


2 answers


You can treat inf values ​​as 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 

      

+4


source


One possible solution:



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

      

+2


source







All Articles