How to sort DataFrame by column in pandas?

Python

Pandas DataFrame – Sort by column

To sort the rows of a DataFrame by columns, use pandas.DataFrame.sort_values() method with arguments by=column_name. The sort_values() method does not modify the original DataFrame, but returns the sorted DataFrame.

You can sort the data frame in ascending or descending order of column values. In this tutorial, we will go through some example programs where we will sort the data frame in ascending or descending order.

Example 1: Sort DataFrame by a column in ascending order

The default sort order of the sort_values() function is ascending. In this example, we will create a data frame 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)

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 ascending order of the column algebra.

 

Example 2: Sort DataFrame by a column in descending order

To sort the dataframe in one column descending order, switch ascending=False argument with sort_values() method. . In this example, we will create a data frame 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)

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 descending order of the column algebra.

Summary

In this guide we have learned how to sort a DataFrame in ascending and descending order, using sort_values(), with the help of detailed Python example programs.

Hope this helps!

Source link

Share: