How to Sort a Pandas DataFrame by Both Index and Column?
Last Updated :
31 Jul, 2023
In this article, we will discuss how to sort a Pandas dataframe by both index and columns.
Sort DataFrame based on Index
We can sort a Pandas DataFrame based on Index and column using sort_index method.
- To sort the DataFrame based on the index we need to pass axis=0 as a parameter to sort_index method.
- To sort the DataFrame based on the column name then we need to pass axis=1 as a parameter to sort_index method.
Syntax
DataFrame_Name.sort_index(axis=0, ascending=True, inplace=False, kind='quicksort')
Parameters
- axis- Specifies on which basis to sort whether based on index or column. By default, it sorts based on index i.e. axis=0.
- ascending- Specifies on which order to sort whether in ascending or descending order. It accepts True or False. By default it is True.
- inplace- It specifies that the changes to the DataFrame is Temporary or Permanent. inplace=False indicates temporary and True indicates permanent.
- kind- Specifies which sorting algorithm to use. It accepts quicksort, mergesort, heapsort, etc. By default, it is quicksort if not mentioned.
DataFrame
|
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.
Python3
# import necessary packages
import pandas as pd
# create 2 dataframes with different indexes
hostelCandidates1 = pd.DataFrame({'col2': [150, 170, 160],
'col1': [70, 55, 60]},
index=[3, 2, 1])
print('original DataFrame')
print(hostelCandidates1)
# sorted temporarily based on index labels
print('Sorted by index')
hostelCandidates1.sort_index(axis=0)
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
Sort DataFrame based on columns
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.
Python3
# import necessary packages
import pandas as pd
# create 2 dataframes with different indexes
hostelCandidates1 = pd.DataFrame({'col2': [150, 170, 160],
'col1': [70, 55, 60]},
index=[3, 2, 1])
print('original DataFrame')
print(hostelCandidates1)
# sorted temporarily based on column labels
print('Sorted by column name')
hostelCandidates1.sort_index(axis=1)
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.
Python3
# import necessary packages
import pandas as pd
# create 2 dataframes with different indexes
hostelCandidates1 = pd.DataFrame({'col2': [150, 170, 160],
'col1': [70, 55, 60]},
index=[3, 2, 1])
print('original DataFrame')
print(hostelCandidates1)
# sorted permanently based on column labels
hostelCandidates1.sort_index(axis=1, inplace=True)
print('Modified Original DataFrame')
print(hostelCandidates1)
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
Similar Reads
How to sort a Pandas DataFrame by multiple columns? We are given a DataFrame and our task is to sort it based on multiple columns. This means organizing the data first by one column and then by another within that sorted order. For example, if we want to sort by 'Rank' in ascending order and then by 'Age' in descending order, the output will be a Dat
4 min read
How to Sort a Pandas DataFrame based on column names or row index? Pandas dataframe.sort_index() method sorts objects by labels along the given axis. Basically, the sorting algorithm is applied to the axis labels rather than the actual data in the Dataframe and based on that the data is rearranged. Creating Pandas Dataframe Create a DataFrame object from the Python
3 min read
Sort the Pandas DataFrame by two or more columns In this article, our basic task is to sort the data frame based on two or more columns. For this, Dataframe.sort_values() method is used. This method sorts the data frame in Ascending or Descending order according to the columns passed inside the function. First, Let's Create a Dataframe: Python3 #i
2 min read
How to Convert Index to Column in Pandas Dataframe? Pandas is a powerful tool which is used for data analysis and is built on top of the python library. The Pandas library enables users to create and manipulate dataframes (Tables of data) and time series effectively and efficiently. These dataframes can be used for training and testing machine learni
2 min read
How to convert index in a column of the Pandas dataframe? Each row in a dataframe (i.e level=0) has an index value i.e value from 0 to n-1 index location and there are many ways to convert these index values into a column in a pandas dataframe. First, let's create a Pandas dataframe. Here, we will create a Pandas dataframe regarding student's marks in a pa
4 min read
How to Sort a Pandas DataFrame by Date? In the real world, we can come across datasets of any form that may include the date inside them too. These datasets can be present in any file format like .CSV, .xlsx, .txt, etc. To load this data inside Python, we use a library named Pandas which provides us a plethora of functions and methods to
3 min read