🐍 Python for Everyone

← Back to the quiz

Chapter 24 Exercises 35 min, hands-on

Exercises: Pandas for Data Analysis

How to run these Download starter.py below, then run python3 starter.py from inside the folder you saved it in. These exercises use real pandas — install it first with pip install pandas if you haven't already.

1 Building a sales DataFrame

Write make_sales_df(products, revenues) — build a DataFrame with columns "product" and "revenue" from two plain Python lists.

2 Summarizing a DataFrame

Write revenue_summary(df) — return a dict with the revenue column's total, average, and max.

3 Filtering with a boolean condition

Write big_sales(df, threshold=1000) — return only the rows with revenue above the threshold.

4 Adding a computed column

Write add_tax_column(df, tax_rate) — add a revenue_with_tax column.

5 .loc[] vs. .iloc[]

Write get_row_by_label(df, label) and get_row_by_position(df, position).

6 Handling missing data

Write clean_revenue(df) — fill missing revenue values with 0.

7 Grouping and aggregating

Write total_by_region(df) — one total revenue per region, using groupby().

8 Sorting

Write top_products(df, n=3) — the top n rows by revenue, highest first.

🐞 Task 9 — Debug the Code

This is supposed to return each region's total revenue, but it groups by the wrong column. Find and fix it.

buggy_region_totals.py
def region_totals(df):
    return df.groupby("product")["revenue"].sum()


demo_df = pd.DataFrame({
    "region": ["East", "West", "East"],
    "product": ["Widget", "Gadget", "Gizmo"],
    "revenue": [1200, 950, 1830],
})
print(region_totals(demo_df))
← Back to Quiz Practice Bank →