Sorting Dataframe By Row Index
We begin by generating some random data
import pandas as pd
import numpy as np
sample_df = pd.DataFrame( data=np.random.rand(18).reshape(6,3),
columns=['x-val', 'y-val', 'z-val'] )
sample_df
x-val | y-val | z-val | |
---|---|---|---|
0 | 0.929960 | 0.686751 | 0.002423 |
1 | 0.959458 | 0.654311 | 0.391251 |
2 | 0.537430 | 0.391395 | 0.305878 |
3 | 0.087757 | 0.195576 | 0.768340 |
4 | 0.837864 | 0.353326 | 0.544702 |
5 | 0.535682 | 0.807780 | 0.379437 |
Implementing the column index sort. For column index, we set axis=1. For row index we set axis=0.
sample_df.sort_index(ascending=False, axis=1)
x-val | y-val | z-val | |
---|---|---|---|
5 | 0.535682 | 0.807780 | 0.379437 |
4 | 0.837864 | 0.353326 | 0.544702 |
3 | 0.087757 | 0.195576 | 0.768340 |
2 | 0.537430 | 0.391395 | 0.305878 |
1 | 0.959458 | 0.654311 | 0.391251 |
0 | 0.929960 | 0.686751 | 0.002423 |