Chapter 2 · Section 6 practice
Business Charts
Work from question 1 to 10. Edit your Python box, click Run Code, review the result, then click Submit attempt. Reference answers unlock after all ten attempts are submitted. This records completion, not correctness. Each box runs independently. Progress is saved in this browser.
1. Totals by category
Warm-up. Use loc to select Gifts and Accessories separately; print total Revenue for each.
Write your answer, then run it.
2. Averages by category
Warm-up. Use loc to select each category separately; print its mean Revenue.
Write your answer, then run it.
3. Number of orders
Warm-up. Print the number of rows in each category.
Write your answer, then run it.
4. Available observations
Build your skills. Print group size and non-missing revenue counts.
Write your answer, then run it.
5. Several summaries
Build your skills. Select each category separately with loc. Print its revenue count, sum, and mean.
Write your answer, then run it.
6. Different rankings
Build your skills. Print the category with the largest total, then the one with the largest mean.
Write your answer, then run it.
7. A labelled bar chart
Build your skills. Plot total category revenue as a bar chart. Add a title and both axis labels.
Write your answer, then run it.
8. A labelled histogram
Challenge. Plot this order-revenue distribution using three bins. Add a title and both axis labels.
Write your answer, then run it.
9. Group profit as well as revenue
Challenge. Calculate profit and print group totals for both Revenue and Profit.
Write your answer, then run it.
10. A supported explanation
Challenge. Calculate total revenue and print a finding that names Gifts, its total, and this four-order sample. Avoid making a coupon claim.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
1. Totals by category
import pandas as pd
df = pd.DataFrame(
{
"Category": ["Gifts", "Gifts", "Gifts", "Accessories"],
"Revenue": [100, 100, 100, 200],
}
)
gifts = df.loc[df["Category"] == "Gifts", "Revenue"]
accessories = df.loc[df["Category"] == "Accessories", "Revenue"]
print("Gifts:", gifts.sum())
print("Accessories:", accessories.sum())Expected output
Gifts: 300
Accessories: 200Select Gifts and Accessories separately with loc, then sum each selected Series.
2. Averages by category
import pandas as pd
df = pd.DataFrame(
{
"Category": ["Gifts", "Gifts", "Gifts", "Accessories"],
"Revenue": [100, 100, 100, 200],
}
)
gifts = df.loc[df["Category"] == "Gifts", "Revenue"]
accessories = df.loc[df["Category"] == "Accessories", "Revenue"]
print("Gifts:", gifts.mean())
print("Accessories:", accessories.mean())Expected output
Gifts: 100.0
Accessories: 200.0The mean uses observations within each group.
3. Number of orders
import pandas as pd
df = pd.DataFrame(
{
"Category": ["Gifts", "Gifts", "Gifts", "Accessories"],
"Revenue": [100, 100, 100, 200],
}
)
gifts = df.loc[df["Category"] == "Gifts", "Revenue"]
accessories = df.loc[df["Category"] == "Accessories", "Revenue"]
print("Gifts:", len(gifts))
print("Accessories:", len(accessories))Expected output
Gifts: 3
Accessories: 1len counts selected rows, not units sold.
4. Available observations
import pandas as pd
df = pd.DataFrame({"Store": ["Central", "Central", "Kowloon"], "Revenue": [100, None, 200]})
central = df.loc[df["Store"] == "Central", "Revenue"]
kowloon = df.loc[df["Store"] == "Kowloon", "Revenue"]
print("Central:", len(central), central.count())
print("Kowloon:", len(kowloon), kowloon.count())Expected output
Central: 2 1
Kowloon: 1 1Central has two rows but only one observed revenue.
5. Several summaries
import pandas as pd
df = pd.DataFrame(
{
"Category": ["Gifts", "Gifts", "Gifts", "Accessories"],
"Revenue": [100, 100, 100, 200],
}
)
gifts = df.loc[df["Category"] == "Gifts", "Revenue"]
accessories = df.loc[df["Category"] == "Accessories", "Revenue"]
print("Gifts:", gifts.count(), gifts.sum(), gifts.mean())
print("Accessories:", accessories.count(), accessories.sum(), accessories.mean())Expected output
Gifts: 3 300 100.0
Accessories: 1 200 200.0Select each category, then call count, sum, and mean separately.
6. Different rankings
import pandas as pd
df = pd.DataFrame(
{
"Category": ["Gifts", "Gifts", "Gifts", "Accessories"],
"Revenue": [100, 100, 100, 200],
}
)
gifts = df.loc[df["Category"] == "Gifts", "Revenue"]
accessories = df.loc[df["Category"] == "Accessories", "Revenue"]
totals = pd.Series({"Gifts": gifts.sum(), "Accessories": accessories.sum()})
means = pd.Series({"Gifts": gifts.mean(), "Accessories": accessories.mean()})
print(totals.idxmax())
print(means.idxmax())Expected output
Gifts
AccessoriesMore orders can outweigh a smaller average.
7. A labelled bar chart
import pandas as pd
df = pd.DataFrame(
{
"Category": ["Gifts", "Gifts", "Gifts", "Accessories"],
"Revenue": [100, 100, 100, 200],
}
)
import matplotlib.pyplot as plt
plt.rcParams.update({"font.size": 11})
gifts = df.loc[df["Category"] == "Gifts", "Revenue"]
accessories = df.loc[df["Category"] == "Accessories", "Revenue"]
totals = pd.Series({"Gifts": gifts.sum(), "Accessories": accessories.sum()})
ax = totals.plot.bar(color="#008080", rot=0, figsize=(6, 3))
ax.set(title="Revenue by category", xlabel="Category", ylabel="Revenue (HKD)")
print("Bar chart created.")
plt.tight_layout()
plt.show()Expected output
Bar chart created.Compare group totals with an explicitly labelled measure.
8. A labelled histogram
import pandas as pd
sales = pd.Series([80, 100, 120, 140, 300, 500])
import matplotlib.pyplot as plt
plt.rcParams.update({"font.size": 11})
ax = sales.plot.hist(bins=3, color="#2a3f5c", figsize=(6, 3))
ax.set(title="Order revenue distribution", xlabel="Revenue (HKD)", ylabel="Number of orders")
print("Histogram created.")
plt.tight_layout()
plt.show()Expected output
Histogram created.A histogram shows numerical intervals, rather than named groups.
9. Group profit as well as revenue
import pandas as pd
df = pd.DataFrame(
{
"Store": ["Central", "Central", "Kowloon"],
"Revenue": [100, 200, 250],
"Cost": [80, 150, 100],
}
)
df["Profit"] = df["Revenue"] - df["Cost"]
central = df.loc[df["Store"] == "Central"]
kowloon = df.loc[df["Store"] == "Kowloon"]
print("Central:", central["Revenue"].sum(), central["Profit"].sum())
print("Kowloon:", kowloon["Revenue"].sum(), kowloon["Profit"].sum())Expected output
Central: 300 70
Kowloon: 250 150Central has greater revenue, while Kowloon has greater profit in these records.
10. A supported explanation
import pandas as pd
df = pd.DataFrame(
{
"Category": ["Gifts", "Gifts", "Gifts", "Accessories"],
"Revenue": [100, 100, 100, 200],
}
)
gifts = df.loc[df["Category"] == "Gifts", "Revenue"]
print(gifts.sum())
print("Gifts contributes HKD 300 in this four-order sample.")Expected output
300
Gifts contributes HKD 300 in this four-order sample.The statement is descriptive and limited to the available records.