Pandas Basics · Exercises
Data

Pandas Basics Exercises

4 exercises that build on the Pandas Basics lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: pandas is a library for working with tables: a DataFrame holds rows and named columns like a spreadsheet, and each column is a Series that you can filter, calculate with and summarise. By the end you can load CSV data into a DataFrame, inspect it, select columns, filter rows, add calculated columns, summarise groups with groupby and sort the results. You will practise: Filter rows by price; Predict the team totals; Fix the top-products report; Average score per subject.

0 / 4 completed

Pandas Basics practice exercises

1. Filter rows by price

Write code Easy

Write a function pricier_than(df, limit) that returns a DataFrame with only the rows of df whose price is greater than limit. Keep all the columns.

Your code
import pandas as pd

books = pd.DataFrame({
    "title": ["Dune", "Emma", "Ulysses", "Matilda", "Beloved"],
    "price": [9.99, 6.50, 14.00, 7.25, 11.80],
})

def pricier_than(df, limit):
    # return only the rows where price > limit
    pass

print(pricier_than(books, 9))

2. Predict the team totals

Predict the output Medium

Read the code and type exactly what it prints.

Read this code
import pandas as pd

df = pd.DataFrame({
    "team": ["red", "blue", "red", "blue", "red"],
    "points": [3, 5, 4, 1, 2],
})
print(len(df))
print(df["points"].sum())
print(df[df["points"] > 2]["team"].tolist())
totals = df.groupby("team")["points"].sum()
print(totals["red"], totals["blue"])

3. Fix the top-products report

Fix the bug Medium

top_products(sales, n) should return the n products with the highest total revenue, biggest first. Right now it returns products in alphabetical order. Find and fix the bug.

Your code
import pandas as pd

sales = pd.DataFrame({
    "product": ["Pen", "Notebook", "Pen", "Bag", "Notebook", "Pen"],
    "revenue": [3.0, 12.0, 4.5, 8.0, 9.0, 6.0],
})

def top_products(sales, n):
    totals = sales.groupby("product")["revenue"].sum()
    totals.sort_values(ascending=False)
    return totals.head(n)

print(top_products(sales, 2))

4. Average score per subject

Write code Hard
  1. Load csv_text into a DataFrame called df using pd.read_csv(io.StringIO(...)).
  2. Write a function subject_averages(df) that returns a Series with the mean score per subject, rounded to 1 decimal place, sorted from highest to lowest.

The function must work for any DataFrame with subject and score columns.

Your code
import io
import pandas as pd

csv_text = """student,subject,score
Asha,maths,78
Ben,maths,64
Asha,art,91
Ben,art,85
Chen,maths,70
Chen,art,88
Asha,history,59
Ben,history,73
"""

# 1) load the data into df

# 2) write subject_averages(df)

Next lessonpandas Selecting Data

More Pandas Basics examples · All Python exercises