Home »
Python »
Python Programs
How to sort rows in pandas DataFrame?
Given a Pandas DataFrame, we have to sort rows.
By Pranit Sharma Last updated : September 22, 2023
Rows in pandas are the different cell (column) values which are aligned horizontally and also provides uniformity. Each row can have same or different value. Rows are generally marked with the index number but in pandas we can also assign index name according to the needs. In pandas, we can create, read, update and delete a column or row value.
Problem statement
Given a Pandas DataFrame, we have to sort rows.
Sorting rows in pandas DataFrame
To sort rows in pandas DataFrame, we will use pandas.DataFrame.sort_values() method. This method works on a particular column and it can sort the values either in ascending order or in descending order.
Note
To work with pandas, we need to import pandas package first, below is the syntax:
import pandas as pd
Let us understand with the help of an example,
Python program to sort rows in pandas DataFrame
# Importing pandas package
import pandas as pd
# Creating a dictionary
d= {
'Name':['Tania','Papia','Arnab','Anurag'],
'Course':['Data Science','Java','Python','Machine Learning'],
'Age':[20,21,19,20],
'College':['JNU','BHU','DU','IIT']
}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display DataFrame
print("DataFrames:\n",df,"\n")
# Sorting the DataFrame by Age
result = df.sort_values(by='Age',ascending=1)
# Display result
print("Sorted DataFrame by Age is:\n",result)
Output
The output of the above program is:
Python Pandas Programs »