![]() |
VOOZH | about |
In this article, we will discuss how to sort a Pandas dataframe by both index and columns.
We can sort a Pandas DataFrame based on Index and column using sort_index method.
Syntax
DataFrame_Name.sort_index(axis=0, ascending=True, inplace=False, kind='quicksort')
Parameters
DataFrame
col2 | col1 | |
|---|---|---|
3 | 150 | 70 |
2 | 170 | 55 |
1 | 160 | 60 |
This was the DataFrame we are using in the below codes for sorting. By specifying axis=0 in sort_index method we can sort the DataFrame. Even if we don't specify axis parameter in sort_index by default it sorts the DataFrame based on row.
Example:
In this example, the DataFrame is a sorted DataFrame based on index labels and this was temporarily sorted in python language.
Output
original DataFrame
col2 col1
3 150 70
2 170 55
1 160 60
Sorted by index col2 col1
1 160 60
2 170 55
3 150 70
To sort the data in the DataFrame on the basis of column names, then we need to pass axis=1 as a parameter to sort_index method in python language.
Output
original DataFrame
col2 col1
3 150 70
2 170 55
1 160 60
Sorted by column name col1 col2
3 70 150
2 55 170
1 60 160
Example Code to sort the DataFrame & save changes permanently on original DataFrame:
Here the sort operation is performed directly on the original DataFrame and changes are saved permanently because of inplace=True argument.
Output
original DataFrame
col2 col1
3 150 70
2 170 55
1 160 60
Modified Original DataFrame
col1 col2
3 70 150
2 55 170
1 60 160