6

I am trying to sort this dataframe, on abs(C)

      A     B     C
0  10.3  11.3 -0.72
1  16.2  10.9 -0.84
2  18.1  15.2  0.64
3  12.2  11.3  0.31
4  17.2  12.2 -0.75
5  11.6  15.4 -0.08
6  16.0  10.4  0.05
7  18.8  14.7 -0.61
8  12.6  16.3  0.85
9  11.6  10.8  0.93

To do that, I have to append a new column D = abs(C), and then sort on D

df['D']= abs (df['C'])
df.sort_values(by=['D'])

Is there a way to do the job in one method?

JJJohn
  • 915
  • 8
  • 26
  • Does this answer your question? [Sort pandas DataFrame with function over column values](https://stackoverflow.com/questions/38662826/sort-pandas-dataframe-with-function-over-column-values) – Mureinik Mar 26 '20 at 07:24

3 Answers3

5

Use Series.argsort for position of absolute values by Series.abs and then change order of rows by DataFrame.iloc:

df2 = df.iloc[df.C.abs().argsort()]
print (df2)
      A     B     C
6  16.0  10.4  0.05
5  11.6  15.4 -0.08
3  12.2  11.3  0.31
7  18.8  14.7 -0.61
2  18.1  15.2  0.64
0  10.3  11.3 -0.72
4  17.2  12.2 -0.75
1  16.2  10.9 -0.84
8  12.6  16.3  0.85
9  11.6  10.8  0.93
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
5

(From my answer in another post:)

Perfect Simple Solution with the Pandas > V_1.1.0:

Use the parameter key in the sort_values function:

import pandas as pd
df = pd.DataFrame({'a': ['a', 'b', 'c', 'd', 'e', 'f'], 'b': [-3, -2, -1, 0, 1, 2]})

df.sort_values(by='b', key=abs)

will yield:

    a   b
3   d   0
2   c   -1
4   e   1
1   b   -2
5   f   2
0   a   -3
Lucecpkn
  • 971
  • 6
  • 9
0
import pandas as pd

ttt = pd.DataFrame({'a': ['a', 'b', 'c', 'd', 'e', 'f'], 'b': [-3, -2, -1, 0, 1, 2]})

# ascending order
ttt_as = ttt.iloc[ttt.b.abs().argsort()]

print (ttt_as)

# descending order
ttt_des = ttt.iloc[ttt.b.abs().argsort()][::-1]

print (ttt_des)
Chris
  • 2,019
  • 5
  • 22
  • 67
Mamun
  • 1