I have a pandas dataframe that I would like to sort in descending order of a column.
Name count
AAAA -1.1
BBBB 0
CCCC -10
DDDD inf
EEEE 3
FFFF NaN
GGGG 30
I want sort count in descending order and move inf
and NaN
rows to the end.
df.sort('count',ascending = False,na_position="last")
pushes NaN
to the end. How to deal with inf
?
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
One of possible solutions:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With