There is a similar question here but not exactly what I'm looking for.
I want to sort a dataframe based on a dictionary that specifies the column(s) to sort by as well as the order for each column.
Example:
df =
+-------+-------+-----------+------+
| Index | Time | Month | Year |
+-------+-------+-----------+------+
| 0 | 13:00 | January | 2018 |
| 1 | 14:30 | March | 2015 |
| 2 | 12:00 | November | 2003 |
| 3 | 10:15 | September | 2012 |
| 4 | 13:30 | October | 2012 |
| 5 | 06:25 | June | 2012 |
| 6 | 07:50 | August | 2019 |
| 7 | 09:20 | May | 2015 |
| 8 | 22:30 | July | 2016 |
| 9 | 23:05 | April | 2013 |
| 10 | 21:10 | April | 2008 |
+-------+-------+-----------+------+
sort_dict = {'Month': 'Ascending', 'Year': 'Descending', 'Time': 'Ascending'}
df.sort_values(by=sort_dict)
df =
+-------+-------+-----------+------+
| Index | Time | Month | Year |
+-------+-------+-----------+------+
| 0 | 13:00 | January | 2018 |
| 1 | 14:30 | March | 2015 |
| 9 | 23:05 | April | 2013 |
| 10 | 21:10 | April | 2008 |
| 7 | 09:20 | May | 2015 |
| 5 | 06:25 | June | 2012 |
| 8 | 22:30 | July | 2016 |
| 6 | 07:50 | August | 2019 |
| 3 | 10:15 | September | 2012 |
| 4 | 13:30 | October | 2012 |
| 2 | 12:00 | November | 2003 |
+-------+-------+-----------+------+
Any help is appreciated thanks!
Column index would also be fine:
sort_dict = {2: 'Ascending', 3: 'Descending', 1: 'Ascending'}