Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Data Analytics Course intermediate pandas Phase 5 — Python for Analytics Python

Filtering, Sorting, and Grouping Data in pandas

Reviewed & accurate
AI Summary

What You Will Learn

  • Filter rows with boolean conditions (pandas WHERE)
  • Sort with sort_values (pandas ORDER BY)
  • Group and aggregate with groupby (pandas GROUP BY)
  • Combine the three for real analysis

Why This Topic Matters

Filter, sort, group — these three operations cover 90% of real pandas work. If you have done lesson 17–21 in SQL, you already know the concepts. This lesson is just the pandas translation.

Sample Data

import pandas as pd

df = pd.DataFrame({
    "order_id": [1, 2, 3, 4, 5, 6, 7, 8],
    "customer": ["Anita", "Ravi", "Mira", "Sam",
                 "Anita", "Ravi", "Mira", "Sam"],
    "city":     ["Mumbai", "Chennai", "Kolkata", "Mumbai",
                 "Mumbai", "Chennai", "Kolkata", "Mumbai"],
    "product":  ["Laptop", "Mouse", "Laptop", "Keyboard",
                 "Mouse", "Laptop", "Keyboard", "Mouse"],
    "amount":   [50000, 500, 60000, 1500, 500, 52000, 1500, 500]
})

1. Filtering Rows — pandas WHERE

Filter by passing a boolean condition inside df[...]:

df[df["amount"] > 1000]

Returns rows where amount > 1000. The condition df["amount"] > 1000 produces a Series of True/False values, one per row. pandas keeps only the True rows.

Multiple conditions — use & (and), | (or), ~ (not)

# Mumbai orders with amount > 1000
df[(df["city"] == "Mumbai") & (df["amount"] > 1000)]

# Orders from Mumbai OR Chennai
df[df["city"].isin(["Mumbai", "Chennai"])]

# Orders NOT from Mumbai
df[df["city"] != "Mumbai"]
# or:
df[~df["city"].isin(["Mumbai"])]
Critical: Always wrap each condition in parentheses when combining with & or |. Without parentheses, Python's operator precedence gives wrong results. This is the #1 pandas filter bug.

String matching

# Customer names starting with 'A'
df[df["customer"].str.startswith("A")]

# Names containing 'av'
df[df["customer"].str.contains("av", case=False)]

Filtering on NULL values

df[df["amount"].isna()]       # rows where amount is NaN
df[df["amount"].notna()]      # rows where amount is not NaN

2. Sorting — pandas ORDER BY

df.sort_values("amount")                       # ascending
df.sort_values("amount", ascending=False)      # descending
df.sort_values(["city", "amount"], ascending=[True, False])
# Sort by city A→Z, then by amount largest first within each city

Sorting with NULLs

df.sort_values("amount", na_position="last")   # default
df.sort_values("amount", na_position="first")  # NULLs at top

3. Grouping — pandas GROUP BY

The pattern is always: df.groupby("column")["value_column"].aggregation().

Single aggregation

df.groupby("city")["amount"].sum()
# city
# Chennai    52500
# Kolkata   61500
# Mumbai    52500
# Name: amount, dtype: int64

Multiple aggregations

df.groupby("city")["amount"].agg(["count", "sum", "mean", "max"])
#           count    sum     mean    max
# city
# Chennai       2  52500  26250.0  52000
# Kolkata       2  61500  30750.0  60000
# Mumbai        2  52500  26250.0  50000

Renaming aggregations

df.groupby("city")["amount"].agg(
    total_sales="sum",
    avg_sale="mean",
    order_count="count"
)

This produces a clean DataFrame with named columns instead of generic "sum", "mean".

Group by multiple columns

df.groupby(["city", "product"])["amount"].sum()
# city     product
# Chennai  Laptop     52000
#          Mouse        500
# Kolkata  Keyboard    1500
#          Laptop     60000
# Mumbai   Keyboard    1500
#          Mouse       1000
# Name: amount, dtype: int64

This is a multi-index Series. To convert it to a flat DataFrame, add .reset_index():

df.groupby(["city", "product"])["amount"].sum().reset_index()

Aggregating different columns differently

df.groupby("city").agg({
    "amount": "sum",
    "order_id": "count"
}).rename(columns={"amount": "total_sales", "order_id": "order_count"})

Combining Filter + Group + Sort

This is the pattern that does real analysis:

(df[df["amount"] > 1000]               # 1. Filter
   .groupby("city")["amount"]          # 2. Group
   .sum()                              # 3. Aggregate
   .sort_values(ascending=False)       # 4. Sort
   .reset_index())                     # 5. Clean index

Read it as: "Take orders above ₹1,000, group by city, sum the amounts, sort largest first, return as a clean DataFrame."

Each step is a method call on the result of the previous one. This chaining style is idiomatic pandas — readable once you get used to it.

The pandas ↔ SQL Translation Table

SQLpandas
SELECT col1, col2 FROM tdf[["col1", "col2"]]
WHERE col > 100df[df["col"] > 100]
WHERE col IN ('a', 'b')df[df["col"].isin(["a", "b"])]
ORDER BY col DESCdf.sort_values("col", ascending=False)
LIMIT 5df.head(5)
SELECT DISTINCT coldf["col"].unique()
SELECT SUM(col) FROM tdf["col"].sum()
SELECT city, SUM(amount) FROM t GROUP BY citydf.groupby("city")["amount"].sum()
SELECT city, SUM(amount) ... HAVING SUM(amount) > 1000g = df.groupby("city")["amount"].sum(); g[g > 1000]
JOINdf1.merge(df2, on="key")

Common Mistakes

  1. Missing parentheses around & / | conditions. The #1 pandas filter bug.
  2. Forgetting that groupby returns a Series or DataFrame with the group column as index. Use reset_index() to flatten.
  3. Using == instead of isin for multi-value filters. df[df["city"] == ["Mumbai", "Chennai"]] does not work; use isin.
  4. Chaining without parentheses. df.filter().groupby().sum().sort_values() works because each method returns a DataFrame. But wrap the whole expression in parentheses if it spans multiple lines.
  5. Modifying a filtered view. df[df["a"] > 5]["b"] = 1 silently fails. Use df.loc[df["a"] > 5, "b"] = 1.

Practical Exercise (20 minutes)

  1. Filter orders where amount > 1000. How many rows?
  2. Filter orders from Mumbai with amount < 1000.
  3. Sort the entire DataFrame by amount, largest first.
  4. Group by city and compute total amount per city.
  5. Group by customer and compute their order count, total spend, and average spend.
  6. Group by city and product, compute total sales. Reset the index for a clean DataFrame.
  7. Combine: filter to Laptop orders only, group by city, sum the amounts, sort descending.

Mini Challenge

Write a one-line pandas chain that returns: for each city, the customer with the highest single order amount. Hint: sort by amount descending, then groupby("city").first(). Confirm the result against the data.

Key Takeaways

  • Filter: df[df["col"] > value]; combine conditions with & / | in parentheses.
  • Sort: df.sort_values("col", ascending=False).
  • Group: df.groupby("col")["value"].agg(...); use .reset_index() to flatten.
  • Chain operations: filter → group → aggregate → sort → reset_index.
  • The pandas ↔ SQL translation table is your cheat sheet.
Course continuity
Previously learned: Lesson 25 introduced the DataFrame.
Today: You learned to filter, sort, and group — the SQL operations in pandas form.
Next: Lesson 27 covers cleaning: missing values, duplicates, type conversion — the unglamorous 80% of real analytics.

FAQ

What is the difference between agg("sum") and .sum()?

Functionally the same for a single aggregation. agg is more flexible — you can pass a list of functions (agg(["sum", "mean"])) or rename them (agg(total="sum")). Use .sum() for simple cases, .agg() for anything complex.

Why does groupby sometimes return a Series and sometimes a DataFrame?

If you select a single column to aggregate (df.groupby("city")["amount"].sum()), you get a Series. If you select multiple columns or use agg with multiple functions, you get a DataFrame. Add reset_index() to always get a flat DataFrame.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments