Python for Data Science: Chapter 5: NumPy and Pandas Libraries

Pandas: Sort and Rank

Python library

The sort_index() function is used to sort series by index labels. The Dataframe.rank() function of Pandas is used to rank the data in different ways.

Sort and Rank

 

1) Sorting

The sort_index() function is used to sort series by index labels

Python program

import pandas as pd

s = pd.Series(["Archana", "Varsha","Rashmi","Usha"],index=[3,1,4,2])

print("‒‒‒‒‒‒‒‒‒‒‒‒Before‒‒‒‒‒‒‒‒‒‒‒‒‒")

print(s)

print("‒‒‒‒‒‒‒‒ After ‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒")

print(s.sort_index())

Output


For displaying the data in descending order we write

print(s.sort_index(ascending=False))

We can also sort the data by values. The sort_values() function is used for that,

Syntax

dataframe.sort_values(by, axis, ascending, inplace, kind, na_position, ignore_index, key)

•  by: It specifies labels to sort by bq es asbasq hoqmi

•  axis: The values can be 0,1,'index', 'columns'. The default 0. The axis to be sorted.

•  ascending: bool or list of bool, default True. Sort ascending vs. descending. Specify list for multiple sort orders. If this is a list of bools, must match the length of the by.

•  inplace: bool, default False. If True, perform operation in‒place

•  kind: {'quicksort', 'mergesort', 'heapsort'}, default 'quicksort'. Choice of sorting algorithm. See also ndarray.np.sort for more information. Mergesort is the only stable algorithm. For DataFrames, this option is only applied when sorting on a single column or label.

na_position : {'first', 'last'}, default 'last'. first puts NaNs at the beginning, last puts NaNs at the end.

Python code

import pandas as pd

students = {

'Names':["Vedant","Mayuresh","Ishwari","Himani","Varad","Aakash"],

'Courses':["Python","Java", "DevOps", "Hadoop","FullStack","Blockchain"],

'Fees':[20000,10000,15000,14000,15000,21000],

'Duration': ['40days', '60days', '60days','40days', '90days', '80days']

}

index_labels = ['s1','s2', 's3','s4', 's5','s6']

df = pd.DataFrame(students, index=index_labels)

print(df)

print("‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒Sorting by Names‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒")

df1 = df.sort_values(by='Names')

print(df1)

print("‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒Sorting by Courses‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒‒")

df2 = df.sort_values(by='Fees')

print(df2)

Output


 

2) Ranking

The Dataframe.rank() function of Pandas is used to rank the data in different ways. After sorting (by default in ascending order), the position is used to determine the rank that is returned. If data contains equal values, then they are assigned with the average of the ranks of each value by default.

The string values are ranked alphabetically in ascending order if there is any missing value, they are ignored in the ranking and ranked as NaN.

Following example illustrates the use of rank() function.

Python code

import pandas as pd

persons = {

'Names': ["Vedant","Mayuresh", "Ishwari", "Himani", "Varad","Aakash"]

}

index labels = ['s1','s2','s3°, 's4','s5','s6']

df = pd.DataFrame(persons,index=index_labels)

print(df)

df['Ranked_Names']=df['Names'].rank()

print("Ranking of Pandas Dataframe Names Column:\n",df)

Output


Code explanation: In above code,

We have created a data frame containing some names. Then we have applied rank( ) function on the names column. The names are ranked alphabetically in ascending order. Another column named Ranked_Names is created and the corresponding ranks are stored in that columns.

For instance the name "Akash" has a rank 1.0, "Himani" has a rank 2.0 because alphabetically A comes before H.

 

Python for Data Science: Chapter 5: NumPy and Pandas Libraries : Tag: Computer Programming, Python, Data Science : Python library - Pandas: Sort and Rank


Python for Data Science: Chapter 5: NumPy and Pandas Libraries



Under Subject


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation



Related Subjects


English Essentials II

EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation



Linear Algebra

MA25C02 2nd Semester | 2025 Regulation


Applied Physics (CSIE) II

PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Digital Principles and Computer Organization

CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Basic Electrical and Electronics Engineering

EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Re-Engineering for Innovation

ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science - Laboratory

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation