JESKO GARAGE All topicsViva questions ▶ Open the practice garage

Python PANDAS (DataFrames & structured data manipulation): 14 practice problems

UNIT 3 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.

▶ Practise PANDAS (DataFrames & structured data manipulation) nowAll topics

Theory: PANDAS (DataFrames & structured data manipulation) in Python

THEORY
------
* Series = 1-D labelled array (one column).  DataFrame = 2-D table of Series sharing an INDEX.
      import pandas as pd
      df = pd.DataFrame({"name": ["A", "B"], "marks": [90, 80]})    # dict of columns
      pd.read_csv("file.csv"), pd.read_excel, pd.read_json;   df.to_csv("out.csv", index=False)
* INSPECT   df.head(n) tail info() describe() shape columns dtypes  df["col"].unique() nunique()
            value_counts()   isna().sum()
* SELECT    df["col"] -> Series     df[["a", "b"]] -> DataFrame
            df.loc[row_label, "col"]   (by LABEL, slice end INCLUDED)
            df.iloc[0, 1]              (by POSITION, slice end excluded)
* FILTER    df[df["marks"] > 80]     df[(df.a > 1) & (df.b == "x")]  (& | ~, brackets!)
            df[df["city"].isin(["Pune", "Delhi"])]    df.query("marks > 80")
* SORT      df.sort_values("marks", ascending=False)   df.sort_values(["a", "b"])   df.nlargest(3, "marks")
* NEW COLS  df["total"] = df["qty"] * df["price"]     (vectorized, no loop)
            df["grade"] = df["marks"].apply(func)     df["x"].map({"a": 1})    np.where(cond, a, b)
            df.assign(total=lambda d: d.qty * d.price)
* MISSING   isna(), dropna(), fillna(value / df["c"].mean()), NaN is ignored by mean/sum
* GROUPBY   split -> apply -> combine
            df.groupby("city")["revenue"].sum()
            df.groupby("city").agg(orders=("order_id", "count"), revenue=("revenue", "sum"))
* COMBINE   pd.merge(left, right, on="key", how="left"/"inner"/"outer")   pd.concat([df1, df2])
* RESHAPE   df.pivot_table(index="city", columns="product", values="qty", aggfunc="sum", fill_value=0)
* STRINGS   df["name"].str.strip().str.title()   .str.contains("x")   .str.len()
* DATES     pd.to_datetime(df["date"]);   df["date"].dt.month / .dt.year / .dt.to_period("M")
* After filtering/sorting, df.reset_index(drop=True) gives a clean 0..n-1 index.
* Most methods return a NEW DataFrame — assign the result (df = df.dropna()).
* Getting plain Python: series.tolist(), series.to_dict(), df.to_dict("records")

14 PANDAS (DataFrames & structured data manipulation) practice problems

1. Total Revenue — vectorized column maths

Easy2 ways to solve
📤 OUTPUT: return an int, e.g. 197350. Use `return`, not print().
Return the sum of qty * price as a Python int.      total_revenue(orders_df()) -> 197350
Solve “Total Revenue — vectorized column maths” in your browser →

2. Orders per Customer — value_counts

Easy2 ways to solve
📤 OUTPUT: return a dict, e.g. {'Asha': 3, 'Ben': 2, 'Dia': 2, 'Eli': 1}. Use `return`, not print().
Return {customer: number_of_orders}.   -> {"Asha": 3, "Ben": 2, "Dia": 2, "Eli": 1}
Solve “Orders per Customer — value_counts” in your browser →

3. Best-Selling Product by Quantity — groupby + idxmax

Easy2 ways to solve
📤 OUTPUT: return a str (text), e.g. 'Mouse'. Use `return`, not print().
    best_selling_product(orders_df()) -> "Mouse"   (2 + 1 + 3 = 6 units)
Solve “Best-Selling Product by Quantity — groupby + idxmax” in your browser →

4. Fill Missing Ratings — fillna with the mean

Easy2 ways to solve
📤 OUTPUT: return a list, e.g. [5.0, 4.0, 3.83, 5.0, 3.0, 4.0, 3.83, 2.0]. Use `return`, not print().
Return the rating column as a list after replacing NaN with the column mean rounded to 2.
    -> [5.0, 4.0, 3.83, 5.0, 3.0, 4.0, 3.83, 2.0]
Solve “Fill Missing Ratings — fillna with the mean” in your browser →

5. High-Value Orders — new column + filter + sort

Medium1 way to solve
📤 OUTPUT: return a list, e.g. [106, 101, 105, 104]. Use `return`, not print().
Return order_ids with revenue >= min_revenue, sorted by revenue DESCENDING.
    big_orders(orders_df(), 30000) -> [106, 101, 105, 104]
Solve “High-Value Orders — new column + filter + sort” in your browser →

6. Customer Summary Table — groupby + agg + sort + reset_index

Medium1 way to solve
📤 OUTPUT: return a DataFrame with columns ["customer", "orders", "revenue"], sorted by revenue DESC,. Use `return`, not print().
Return a DataFrame with columns ["customer", "orders", "revenue"], sorted by revenue DESC,
index 0..n-1.
      customer  orders  revenue
    0     Asha       3    57000
    1      Eli       1    56000
    2      Ben       2    53000
    3      Dia       2    31350
Solve “Customer Summary Table — groupby + agg + sort + reset_index” in your browser →

7. Unique Products per City — groupby + unique

Easy2 ways to solve
📤 OUTPUT: return a dict, e.g. {'Delhi': ['Laptop', 'Mouse'], 'Mumbai': ['Mou…. Use `return`, not print().
Return {city: sorted list of distinct products}.
    -> {"Delhi": ["Laptop", "Mouse"], "Mumbai": ["Mouse", "Phone"], "Pune": ["Keyboard", "Laptop", "Mouse", "Phone"]}
Solve “Unique Products per City — groupby + unique” in your browser →

8. Clean Messy Names — .str accessor + drop_duplicates

Easy2 ways to solve
📤 OUTPUT: return a list, e.g. ['Asha', 'Ben', 'Chen']. Use `return`, not print().
names: a list of raw strings. Strip spaces, Title-case, drop duplicates (keep first), return a list.
    clean_customer_names(["  asha ", "BEN", "Asha", "ben  ", "chen"]) -> ["Asha", "Ben", "Chen"]
Solve “Clean Messy Names — .str accessor + drop_duplicates” in your browser →

9. Monthly Sales — dates with to_datetime + dt.to_period

Medium1 way to solve
📤 OUTPUT: return a dict, e.g. {'2024-01': 150, '2024-02': 70}. Use `return`, not print().
Return {"YYYY-MM": total} for each month present.
    monthly_totals(["2024-01-05", "2024-01-20", "2024-02-01"], [100, 50, 70]) -> {"2024-01": 150, "2024-02": 70}
Solve “Monthly Sales — dates with to_datetime + dt.to_period” in your browser →

10. Join Customer Tiers — pd.merge (left join) + fillna

Medium2 ways to solve
📤 OUTPUT: return a dict, e.g. {101: 'Gold', 102: 'Silver', 103: 'Gold', 104:…. Use `return`, not print().
tiers: DataFrame with columns customer, tier (not every customer is present).
Return {order_id: tier}, using "Unknown" when a customer has no tier.
    tiers = pd.DataFrame({"customer": ["Asha", "Ben"], "tier": ["Gold", "Silver"]})
    -> {101: "Gold", 102: "Silver", 103: "Gold", 104: "Unknown", ...}
Solve “Join Customer Tiers — pd.merge (left join) + fillna” in your browser →

11. Bucket Ratings — apply / np.select

Medium2 ways to solve
📤 OUTPUT: return a dict, e.g. {'good': 4, 'bad': 2, 'none': 2}. Use `return`, not print().
"good" (>= 4), "bad" (< 4), "none" (NaN). Return {bucket: count}.
    -> {"good": 4, "bad": 2, "none": 2}
Solve “Bucket Ratings — apply / np.select” in your browser →

12. Pivot Table — city x product quantities

Medium2 ways to solve
📤 OUTPUT: return df.pivot_table(index="city", columns="product", values="qty", aggfunc="sum", fill_value=0). Use `return`, not print().
Return df.pivot_table(index="city", columns="product", values="qty", aggfunc="sum", fill_value=0)
as a nested dict {city: {product: qty}} including zeros (Python ints).
    result["Pune"] -> {"Keyboard": 1, "Laptop": 1, "Mouse": 1, "Phone": 2}
Solve “Pivot Table — city x product quantities” in your browser →

13. Restaurant Partner KPIs — interview at a food-delivery company (analytics team)

Project1 way to solve
📤 OUTPUT: return a DataFrame with columns ["restaurant", "orders", "revenue", "avg_rating", "late_pct"]:. Use `return`, not print().
Interviewer: "Every week we send each restaurant its KPIs. Build the table with Pandas."
Return a DataFrame with columns ["restaurant", "orders", "revenue", "avg_rating", "late_pct"]:
  orders = count, revenue = sum of amount, avg_rating = mean of ratings ignoring missing (rounded to 2),
  late_pct = % of orders with delivery_min > 40 (rounded to 1).
Sorted by revenue DESC, index 0..n-1.
Solve “Restaurant Partner KPIs — interview at a food-delivery company (analytics team)” in your browser →

14. Stage 16 — Compiler Profiler (which stage is slow?) with Pandas

Compiler1 way to solve
📤 OUTPUT: return a DataFrame with columns ["stage", "runs", "mean_ms", "max_ms", "share_pct"]. Use `return`, not print().
timings: list of {"stage", "ms"} from many compiler runs.
Return a DataFrame with columns ["stage", "runs", "mean_ms", "max_ms", "share_pct"]
  share_pct = stage total / grand total * 100 (rounded to 1); mean_ms rounded to 2.
Sorted by mean_ms DESC, index 0..n-1.
Solve “Stage 16 — Compiler Profiler (which stage is slow?) with Pandas” in your browser →

← NUMPY (with PREREQUISITES: vectors, matrices, basic statistics) DATA VISUALIZATION: Matplotlib & Seaborn →