Pandas Sorting and Filtering Practice Questions with Solutions

Sorting and filtering are essential operations in Pandas for organizing and analyzing data efficiently. Sorting helps arrange data in ascending or descending order, while filtering allows you to retrieve only the records that satisfy specific conditions. Pandas provides powerful methods such as sort_values(), sort_index(), and Boolean indexing to simplify these tasks. In this chapter, you’ll learn how to sort and filter DataFrames using practical examples. Pandas Sorting and Filtering Practice questions with solutions help to understand the concepts.


1. Python Program to Sort a DataFrame by a Single Column (Ascending)

Problem Statement

Write a Python program to sort a DataFrame by the Marks column in ascending order.

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Marks": [85, 90, 78, 88]
}

df = pd.DataFrame(data)

sorted_df = df.sort_values(by="Marks")

print(sorted_df)

Sample Output

     Name  Marks
2   Priya     78
0   Rahul     85
3   Sneha     88
1    Aman     90

Explanation

The sort_values() function sorts the DataFrame based on the specified column. By default, the sorting order is ascending.

Concepts Covered

  • sort_values()
  • Ascending Order
  • Data Sorting

2. Python Program to Sort a DataFrame in Descending Order

Problem Statement

Write a Python program to sort the Marks column in descending order.

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Marks": [85, 90, 78, 88]
}

df = pd.DataFrame(data)

sorted_df = df.sort_values(
    by="Marks",
    ascending=False
)

print(sorted_df)

Sample Output

     Name  Marks
1    Aman     90
3   Sneha     88
0   Rahul     85
2   Priya     78

Explanation

Setting ascending=False sorts the data from the highest value to the lowest value.

Concepts Covered

  • sort_values()
  • Descending Order
  • Data Sorting

3. Python Program to Sort by Multiple Columns

Problem Statement

Write a Python program to sort a DataFrame by Age first and then by Marks.

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Age": [20, 20, 19, 20],
    "Marks": [85, 90, 78, 88]
}

df = pd.DataFrame(data)

sorted_df = df.sort_values(
    by=["Age", "Marks"]
)

print(sorted_df)

Sample Output

     Name  Age  Marks
2   Priya   19     78
0   Rahul   20     85
3   Sneha   20     88
1    Aman   20     90

Explanation

The sort_values() function accepts multiple columns. It sorts by the first column and uses the second column when duplicate values occur.

Concepts Covered

  • Multiple Column Sorting
  • sort_values()
  • Hierarchical Sorting

4. Python Program to Sort a DataFrame by Index

Problem Statement

Write a Python program to sort a DataFrame using its index.

Python Solution

import pandas as pd

data = {
    "Marks": [85, 90, 78]
}

df = pd.DataFrame(
    data,
    index=[3, 1, 2]
)

sorted_df = df.sort_index()

print(sorted_df)

Sample Output

   Marks
1     90
2     78
3     85

Explanation

The sort_index() function arranges rows based on the DataFrame index.

Concepts Covered

  • sort_index()
  • Index Sorting
  • DataFrame Index

5. Python Program to Filter Rows with Marks Greater Than 80

Problem Statement

Write a Python program to display students whose Marks are greater than 80.

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Marks": [85, 90, 78, 88]
}

df = pd.DataFrame(data)

filtered_df = df[df["Marks"] > 80]

print(filtered_df)

Sample Output

     Name  Marks
0   Rahul     85
1    Aman     90
3   Sneha     88

Explanation

Boolean indexing filters rows that satisfy the specified condition.

Concepts Covered

  • Boolean Indexing
  • Data Filtering
  • Conditional Selection

6. Python Program to Filter Rows Using Multiple Conditions (AND)

Problem Statement

Write a Python program to display students whose Age is greater than 20 and Marks are greater than or equal to 85.

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Age": [20, 21, 19, 22],
    "Marks": [85, 90, 78, 88]
}

df = pd.DataFrame(data)

filtered_df = df[
    (df["Age"] > 20) &
    (df["Marks"] >= 85)
]

print(filtered_df)

Sample Output

     Name  Age  Marks
1    Aman   21     90
3   Sneha   22     88

Explanation

The & operator combines multiple conditions. Each condition must be enclosed in parentheses.

Concepts Covered

  • Boolean Indexing
  • AND Operator
  • Multiple Conditions

7. Python Program to Filter Rows Using Multiple Conditions (OR)

Problem Statement

Write a Python program to display students whose Marks are greater than or equal to 90 or Age is less than 20.

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Age": [20, 21, 19, 22],
    "Marks": [85, 90, 78, 88]
}

df = pd.DataFrame(data)

filtered_df = df[
    (df["Marks"] >= 90) |
    (df["Age"] < 20)
]

print(filtered_df)

Sample Output

     Name  Age  Marks
1    Aman   21     90
2   Priya   19     78

Explanation

The | operator returns rows that satisfy at least one of the specified conditions.

Concepts Covered

  • OR Operator
  • Boolean Filtering
  • Conditional Selection

8. Python Program to Filter Rows Using isin()

Problem Statement

Write a Python program to display students enrolled in either Python or Data Science courses.

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Course": [
        "Python",
        "Java",
        "Data Science",
        "Python"
    ]
}

df = pd.DataFrame(data)

filtered_df = df[
    df["Course"].isin(
        ["Python", "Data Science"]
    )
]

print(filtered_df)

Sample Output

     Name         Course
0   Rahul         Python
2   Priya   Data Science
3   Sneha         Python

Explanation

The isin() function filters rows whose values match any item in the provided list.

Concepts Covered

  • isin()
  • Membership Filtering
  • Boolean Indexing

9. Python Program to Filter Rows Using Between a Range

Problem Statement

Write a Python program to display students whose Marks are between 80 and 90.

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Marks": [85, 90, 78, 88]
}

df = pd.DataFrame(data)

filtered_df = df[
    df["Marks"].between(80, 90)
]

print(filtered_df)

Sample Output

     Name  Marks
0   Rahul     85
1    Aman     90
3   Sneha     88

Explanation

The between() function returns rows whose values lie within the specified range, including both endpoints.

Concepts Covered

  • between()
  • Range Filtering
  • Data Selection

10. Python Program to Filter Rows Using query()

Problem Statement

Write a Python program to display students whose Marks are greater than 80 using the query() function.

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Marks": [85, 90, 78, 88]
}

df = pd.DataFrame(data)

filtered_df = df.query("Marks > 80")

print(filtered_df)

Sample Output

     Name  Marks
0   Rahul     85
1    Aman     90
3   Sneha     88

Explanation

The query() function provides a clean and readable way to filter rows using string expressions.

Concepts Covered

  • query()
  • Data Filtering
  • Conditional Selection

11. Python Program to Filter Rows Using str.contains()

Problem Statement

Write a Python program to display students whose names contain the letter “a” (case-insensitive).

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"]
}

df = pd.DataFrame(data)

filtered_df = df[
    df["Name"].str.contains(
        "a",
        case=False
    )
]

print(filtered_df)

Sample Output

     Name
0   Rahul
1    Aman
2   Priya
3   Sneha

Explanation

The str.contains() method filters rows based on whether the specified text exists in a string column.

Concepts Covered

  • str.contains()
  • String Filtering
  • Text Search

12. Python Program to Filter Rows Using notnull()

Problem Statement

Write a Python program to display only the rows where the Marks column does not contain missing values.

Python Solution

import pandas as pd
import numpy as np

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Marks": [85, np.nan, 78, 92]
}

df = pd.DataFrame(data)

filtered_df = df[
    df["Marks"].notnull()
]

print(filtered_df)

Sample Output

     Name  Marks
0   Rahul   85.0
2   Priya   78.0
3   Sneha   92.0

Explanation

The notnull() function filters rows containing valid values while excluding missing (NaN) values.

Concepts Covered

  • notnull()
  • Missing Values
  • Data Filtering

13. Python Program to Sort by Multiple Columns with Different Orders

Problem Statement

Write a Python program to sort data by Age in ascending order and Marks in descending order.

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Age": [20, 20, 19, 20],
    "Marks": [85, 90, 78, 88]
}

df = pd.DataFrame(data)

sorted_df = df.sort_values(
    by=["Age", "Marks"],
    ascending=[True, False]
)

print(sorted_df)

Sample Output

     Name  Age  Marks
2   Priya   19     78
1    Aman   20     90
3   Sneha   20     88
0   Rahul   20     85

Explanation

The ascending parameter accepts a list, allowing different sorting orders for each column.

Concepts Covered

  • Multi-Level Sorting
  • sort_values()
  • Ascending and Descending Order

14. Python Program to Get Top 3 Highest Marks

Problem Statement

Write a Python program to display the top three students with the highest marks.

Python Solution

import pandas as pd

data = {
    "Name": [
        "Rahul",
        "Aman",
        "Priya",
        "Sneha",
        "Rohit"
    ],
    "Marks": [85, 90, 78, 88, 95]
}

df = pd.DataFrame(data)

top_students = df.nlargest(3, "Marks")

print(top_students)

Sample Output

     Name  Marks
4   Rohit     95
1    Aman     90
3   Sneha     88

Explanation

The nlargest() function returns the rows containing the highest values from the specified column.

Concepts Covered

  • nlargest()
  • Top Records
  • Data Ranking

15. Python Program to Get Bottom 2 Lowest Marks

Problem Statement

Write a Python program to display the two students with the lowest marks.

Python Solution

import pandas as pd

data = {
    "Name": [
        "Rahul",
        "Aman",
        "Priya",
        "Sneha",
        "Rohit"
    ],
    "Marks": [85, 90, 78, 88, 95]
}

df = pd.DataFrame(data)

bottom_students = df.nsmallest(2, "Marks")

print(bottom_students)

Sample Output

     Name  Marks
2   Priya     78
0   Rahul     85

Explanation

The nsmallest() function quickly returns rows with the lowest values from the selected column.

Concepts Covered

  • nsmallest()
  • Lowest Values
  • Data Ranking

16. Python Program to Filter Rows Using loc[]

Problem Statement

Write a Python program to display students whose Marks are greater than or equal to 85 using the loc[] indexer.

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Marks": [85, 90, 78, 88]
}

df = pd.DataFrame(data)

filtered_df = df.loc[df["Marks"] >= 85]

print(filtered_df)

Sample Output

     Name  Marks
0   Rahul     85
1    Aman     90
3   Sneha     88

Explanation

The loc[] indexer selects rows based on labels and Boolean conditions. It is commonly used for filtering and selecting specific rows.

Concepts Covered

  • loc[]
  • Boolean Filtering
  • Label-Based Indexing

17. Python Program to Filter Rows Using iloc[]

Problem Statement

Write a Python program to display the first three rows and the first two columns of a DataFrame using iloc[].

Python Solution

import pandas as pd

data = {
    "Name": ["Rahul", "Aman", "Priya", "Sneha"],
    "Age": [20, 21, 19, 22],
    "Marks": [85, 90, 78, 88]
}

df = pd.DataFrame(data)

print(df.iloc[0:3, 0:2])

Sample Output

     Name  Age
0   Rahul   20
1    Aman   21
2   Priya   19

Explanation

The iloc[] indexer selects rows and columns based on their integer positions rather than labels.

Concepts Covered

  • iloc[]
  • Position-Based Indexing
  • Data Selection

Chapter Summary

In this chapter, you learned how to organize and retrieve data efficiently using Pandas sorting and filtering techniques. You explored sorting data by one or multiple columns, sorting by index, filtering rows using Boolean conditions, combining multiple conditions with AND and OR operators, filtering using isin(), between(), query(), str.contains(), and notnull(), retrieving the highest and lowest records using nlargest() and nsmallest(), and selecting filtered data using loc[] and iloc[].


Key Takeaways

  • Use sort_values() to sort DataFrames by one or multiple columns.
  • Use sort_index() to sort rows based on index values.
  • Boolean indexing is the most common way to filter rows.
  • Combine conditions using & (AND) and | (OR).
  • Use isin() to filter values from a list.
  • Use between() to filter values within a range.
  • query() provides a cleaner syntax for filtering.
  • str.contains() is useful for text-based filtering.
  • nlargest() and nsmallest() return the highest and lowest records efficiently.
  • loc[] uses labels, while iloc[] uses integer positions for data selection.

Frequently Asked Questions (FAQs)

1. Which function is used to sort a DataFrame by a column?

Use the sort_values() function.

df.sort_values(by="Marks")

2. How do you sort data in descending order?

Use the ascending=False parameter.

df.sort_values(
    by="Marks",
    ascending=False
)

3. How do you filter rows based on a condition?

Use Boolean indexing.

df[df["Marks"] > 80]

4. What is the purpose of the query() function?

The query() function filters rows using a readable string expression.

df.query("Marks >= 85")

5. What is the difference between loc[] and iloc[]?

  • loc[] selects data using labels.
  • iloc[] selects data using integer positions.

6. Which function returns the highest values from a column?

Use the nlargest() function.

df.nlargest(3, "Marks")

7. Which function returns the lowest values from a column?

Use the nsmallest() function.

df.nsmallest(2, "Marks")

8. Why are sorting and filtering important in Pandas?

Sorting and filtering make it easier to organize, search, analyze, and extract meaningful information from datasets. They are among the most frequently used operations in data analysis, reporting, and machine learning workflows.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top