0

With a pandas dataframe, we can sort the dataframe based on the value of a row

dfObj = dfObj.sort_values(by='b', axis=1, ascending=False)

May we do it based on the absolute value (or more generally, a function) of a row? I expect something like

dfObj = dfObj.sort_values(by=abs('b'), axis=1, ascending=False)

If it can't work, how can we produce a row equivalent to the absolute value of row 'b' and then sort?

Thanks!!

  • Does [this](https://stackoverflow.com/questions/13838405/custom-sorting-in-pandas-dataframe) help you? – rpanai Apr 20 '20 at 01:46
  • Thanks @rpanai ```df['m'] = pd.Categorical(df['m'], ["March", "April", "Dec"])``` How can I add a row instead of a column? – user2644687 Apr 20 '20 at 01:51
  • Check [this](https://stackoverflow.com/questions/30486263/sorting-by-absolute-value-without-changing-the-data) – tidakdiinginkan Apr 20 '20 at 02:17

1 Answers1

0

You are very close, you can do:

dfObj = dfObj.sort_values(dfObj.loc['b'].abs(), axis=1, ascending=False)
Allen Qin
  • 19,507
  • 8
  • 51
  • 67