Home > Mobile >  How to sort (rearrange) DataFrame by descending last row value, and rearrange columns respectively
How to sort (rearrange) DataFrame by descending last row value, and rearrange columns respectively

Time:02-18

I am working my quant. I have a set of data which is date-indexed, and the output heatmap is not sorted in any way. What I want is to sort the values of the last day (today if the case) numbers descending, and rearrange the columns respectively.

raw data:

ts_code       FJ   AIR   Duty   HQ   Engine Gene  FDA   WLC   SPE   TAXI  
trade_date                                                                
20220128     1.86  2.03  2.54  1.40   1.24  1.33  0.68  0.30  0.45  2.50  
20220207     1.93  0.91  1.69 -0.14   0.93  1.44  0.27  1.06  1.28  1.35  
20220208     2.38  1.47  2.52  2.59   0.49  1.29  1.57 -0.17  0.76  4.02  
20220209     1.89  1.81  0.69  1.71   1.53  1.16  2.20  1.96  1.59  2.51  
20220210     0.41 -0.47  1.29 -0.22  -1.03  0.07 -0.36 -1.52 -1.23  0.31  
20220211    -1.07 -1.54 -0.85 -2.15  -2.60 -2.89 -2.64 -3.26 -2.10 -0.87  
20220214    -0.63  0.57  1.19  0.37   0.64  0.42 -0.69  0.62 -0.29 -0.10  
20220215    -1.09  0.37 -1.62  0.22   1.80  1.37  0.53  1.57  1.80  0.14  
20220216     1.68  0.49  1.15  1.12   0.55  0.95  1.21  1.07  0.69  1.42  
20220217    -1.39 -0.25 -1.59 -1.16   0.18 -0.67  1.04  0.08 -0.11 -2.29 

enter image description here

I tried Transpose first, sorted, and transpose back. A bit disastrous. Is there a simpler way of doing such?

CodePudding user response:

You can use pandas.DataFrame.sort_values method and set axis=1 in the argument. and sort the dataframe according to the values of the last row.

sorted_df = df.sort_values(df.last_valid_index(), axis=1,ascending=False)
  • Related