Contents
Pandas DataFrame – Sort by Column
To sort the rows of a DataFrame by a column, use pandas.DataFrame.sort_values()
method with the argument by=column_name
. The sort_values() method does not modify the original DataFrame, but returns the sorted DataFrame.
You can sort the dataframe in ascending or descending order of the column values. In this tutorial, we shall go through some example programs, where we shall sort dataframe in ascending or descending order.
Example 1: Sort DataFrame by a Column in Ascending Order
The default sorting order of sort_values() function is ascending order. In this example, we will create a dataframe and sort the rows by a specific column in ascending order.
Python Program
import pandas as pd
data = {'name': ['Somu', 'Kiku', 'Amol', 'Lini'],
'physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],
'algebra': [78, 88, 82, 87]}
#create dataframe
df_marks = pd.DataFrame(data)
#sort dataframe
sorted_df = df_marks.sort_values(by='algebra')
print(sorted_df)
Run Output
name physics chemistry algebra
0 Somu 68 84 78
2 Amol 77 73 82
3 Lini 78 69 87
1 Kiku 74 56 88
You can see that the rows are sorted based on the increasing order of the column algebra.
Example 2: Sort DataFrame by a Column in Descending Order
To sort the dataframe in descending order a column, pass ascending=False
argument to the sort_values()
method. . In this example, we will create a dataframe and sort the rows by a specific column in descending order.
Python Program
import pandas as pd
data = {'name': ['Somu', 'Kiku', 'Amol', 'Lini'],
'physics': [68, 74, 77, 78],
'chemistry': [84, 56, 73, 69],
'algebra': [78, 88, 82, 87]}
#create dataframe
df_marks = pd.DataFrame(data)
#sort dataframe
sorted_df = df_marks.sort_values(by='algebra', ascending=False)
print(sorted_df)
Run Output
name physics chemistry algebra
1 Kiku 74 56 88
3 Lini 78 69 87
2 Amol 77 73 82
0 Somu 68 84 78
You can see that the rows are sorted based on the decreasing order of the column algebra.
Summary
In this Pandas Tutorial, we learned to sort DataFrame in ascending and descending orders, using sort_values(), with the help of well detailed Python example programs.