How to Sort Dataframe in Python
We can use the sort_values()
function in Pandas to sort a Pandas DataFrame.
In this article, we will learn to sort a dataframe in many ways.
We are performing the sorting in the below dummy data.
1. Sort Pandas DataFrame in an ascending order
# sort - ascending order import pandas as pd import numpy as np di = {'Name': ['abi', 'hari', 'taylor', 'dev'], 'Age': [21, 20, 21, 20], 'Place': ['yale', 'london', 'delhi', 'mumbai'], } df = pd.DataFrame(di, columns = ['Name', 'Age', 'Place']) # sort Name in ascending order df.sort_values(by = ['Name'], inplace = True) print(df)
Output:
Name Age Place 0 abi 21 yale 3 dev 20 mumbai 1 hari 20 london 2 taylor 21 delhi
2. Sort Pandas DataFrame in an descending order
# sort - descending order import pandas as pd import numpy as np di = {'Name': ['abi', 'hari', 'taylor', 'dev'], 'Age': [21, 20, 21, 20], 'Place': ['yale', 'london', 'delhi', 'mumbai'], } df = pd.DataFrame(di, columns = ['Name', 'Age', 'Place']) # sort Name in descending order df.sort_values(by = ['Name'], inplace = True, ascending = False) print(df)
Output:
Name Age Place 2 taylor 21 delhi 1 hari 20 london 3 dev 20 mumbai 0 abi 21 yale
3. Sort by multiple columns – Case 1
# sort - multiple columns import pandas as pd import numpy as np di = {'Name': ['abi', 'hari', 'taylor', 'dev'], 'Age': [21, 20, 21, 20], 'Place': ['yale', 'london', 'delhi', 'mumbai'], } df = pd.DataFrame(di, columns = ['Name', 'Age', 'Place']) # sort by multiple columns: Place and Age df.sort_values(by = ['Place', 'Age'], inplace = True) print(df)
Output:
Name Age Place 2 taylor 21 delhi 1 hari 20 london 3 dev 20 mumbai 0 abi 21 yale
Note that priority will be more for Place than Age.
Subscribe
Login
Please login to comment
0 Discussion