Sorting Dataframe By Multiple Values
Generating random data.
import pandas as pd
import numpy as np
sample_df = pd.DataFrame({'x-val':[1,1,1,2,2,2], 'y-val':np.random.rand(6), 'z-val':np.random.rand(6)})
sample_df
x-val | y-val | z-val | |
---|---|---|---|
0 | 1 | 0.866973 | 0.074644 |
1 | 1 | 0.945542 | 0.239148 |
2 | 1 | 0.451685 | 0.073848 |
3 | 2 | 0.100797 | 0.684813 |
4 | 2 | 0.105647 | 0.054043 |
5 | 2 | 0.110734 | 0.830431 |
Implementing sorting of x-val and y-val where x-val is descending and y-val is ascending
sample_df.sort_values(by=['x-val', 'y-val'], ascending=[False, True])
x-val | y-val | z-val | |
---|---|---|---|
3 | 2 | 0.100797 | 0.684813 |
4 | 2 | 0.105647 | 0.054043 |
5 | 2 | 0.110734 | 0.830431 |
2 | 1 | 0.451685 | 0.073848 |
0 | 1 | 0.866973 | 0.074644 |
1 | 1 | 0.945542 | 0.239148 |