Pandas Filtering & Sorting

Boolean filters and sort_values.

✍️ 3 exercises + code challenge in this lesson
  • Filter rows: df[df["marks"] > 70]
  • Combine conditions with & (and) and | (or), each in parentheses.
  • df.query("marks > 70") is a readable alternative.
  • Sort: df.sort_values("marks", ascending=False)

Key Takeaways: Pandas Filtering & Sorting

Mastering Pandas Filtering & Sorting helps you write clean and reliable Pandas code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Pandas Filtering & Sorting Code Example

Pandas
import pandas as pd

df = pd.DataFrame({
    "name": ["Ali", "Sara", "Usman", "Hina"],
    "dept": ["IT", "HR", "IT", "Sales"],
    "salary": [120000, 95000, 110000, 88000],
})
print(df[df["salary"] > 100000])
print(df[(df["dept"] == "IT") & (df["salary"] < 115000)])
print(df.sort_values("salary", ascending=False)["name"].tolist())
Output
name dept  salary
0    Ali   IT  120000
2  Usman   IT  110000
    name dept  salary
2  Usman   IT  110000
['Ali', 'Usman', 'Sara', 'Hina']
Free sign-in required · Google login available

Pandas Filtering & Sorting Practice Exercises

Check what you learned in “Pandas Filtering & Sorting”.

/ 3 solved
Fill in the blank

Sort by salary, highest first.

df.sort_values("salary", ascending=)
✓ Correct! Not quite. Try again.
Multiple choice

How do you combine two filter conditions with AND?

✓ Correct! Not quite. Try again.
Code challenge

Print the names of people in the IT department as a list.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services