Home > Mobile >  python pandas sort_values with multiple custom keys
python pandas sort_values with multiple custom keys

Time:11-05

I have a dataframe with 2 columns, I would like to sort column A ascending, and B ascending but using the absolute value. How do I do this? I tried like df.sort_values(by=['A', 'B'], key=lambda x: abs(x)) but it will take the absolute value of both columns and sort ascend.

df = pd.DataFrame({'A': [1,2,-3], 'B': [-1, 2, -3]})

output:


    A   B
0   1   -1
1   2   2
2   -3  -3

Expected output:


    A   B
0   -3  -1
1   1   2
2   2   -3

CodePudding user response:

You can't have multiple sort key because index can't be dissociated. The only way is to sort your columns independently and recreate a dataframe:

>>> df.agg({'A': lambda x: x.sort_values().values,
            'B': lambda x: x.sort_values(key=abs).values}) \
      .apply(pd.Series).T

   A  B
0 -3 -1
1  1  2
2  2 -3

CodePudding user response:

Use numpy.sort, to so sort column A values

df =df.assign(A= np.sort(df['A'].values))



   A  B
0 -3 -1
1  1  2
2  2 -3
  • Related