Sorting dataframe by absolute value of a row

Viewed 327

I have the following dataframe:

import pandas as pd
data = {0: [-1, -14], 1: [-3, 2], 2: [7, 10], 4: [-10, 15]}
df = pd.DataFrame(data)

I know how to sort an specific row:

df.sort_values(by=0, ascending=False, axis=1)

How is it possible to sort the dataframe by the absolute value of the first row? In this case I will have something like:

sorted_data = {0: [-10, 15], 1: [7, 10], 2: [-3, 2], 4: [-1, -14]}
3 Answers

sort series by slicing of row 0 and passing its index to indexing the original df

df_sorted = df[df.iloc[0].abs().sort_values(ascending=False).index]

Out[94]:
    4   2  1   0
0 -10   7 -3  -1
1  15  10  2 -14

Let us try argsort

df = df.iloc[:,(-df.loc[0].abs()).argsort()]

Pandas 1.1 gives a key argument :

df.sort_values(0, axis=1, key=np.abs, ascending=False)


      4  2   1    0
0   -10  7  -3   -1
1   15   10  2  -14
Related