Chapter 2 · Section 4 practice
Feature Engineering and Modifying Tables
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. Calculate revenue
Warm-up. Create Revenue = Units × Price and print its values as a list.
Write your answer, then run it.
2. Total revenue
Warm-up. Calculate Revenue and print its total.
Write your answer, then run it.
3. Product cost
Warm-up. Add ProductCost to this table and print its list.
Write your answer, then run it.
4. Gross profit
Build your skills. Calculate GrossProfit from Revenue and ProductCost, then print its total.
Write your answer, then run it.
5. Order-size labels
Build your skills. Use a comprehension to label observed revenues >= 200 as Large and others as Standard. Print the list.
Write your answer, then run it.
6. Rename a column
Build your skills. Rename Units to Quantity and print the new column labels.
Write your answer, then run it.
7. Keep a smaller table
Build your skills. Drop Price into a new table and print both new and original column labels.
Write your answer, then run it.
8. The two largest orders
Challenge. Calculate Revenue, sort descending, and print labels of the top two records.
Write your answer, then run it.
9. Undefined margins
Challenge. Calculate Margin using only positive Revenue denominators. Print rounded margins as a list.
Write your answer, then run it.
10. Four direction labels
Challenge. Use loc assignments to label positive returns Up, zero Flat, negative Down, and missing Unknown. Print the list.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
1. Calculate revenue
import pandas as pd
df = pd.DataFrame({"Store": ["Central", "Kowloon", "Central", "Kowloon"],
"Units": [2, 1, 4, 3], "Price": [120, 80, 35, 60]},
index=["A", "B", "C", "D"])
df["Revenue"] = df["Units"] * df["Price"]
print(list(df["Revenue"]))Expected output
[240, 80, 140, 180]The products pair observations in the same row.
2. Total revenue
import pandas as pd
df = pd.DataFrame({"Store": ["Central", "Kowloon", "Central", "Kowloon"],
"Units": [2, 1, 4, 3], "Price": [120, 80, 35, 60]},
index=["A", "B", "C", "D"])
df["Revenue"] = df["Units"] * df["Price"]
print(df["Revenue"].sum())Expected output
640Summing order revenues gives the total for these four records.
3. Product cost
import pandas as pd
df = pd.DataFrame({"Units": [2, 3, 1], "UnitCost": [70, 22, 50]})
df["ProductCost"] = df["Units"] * df["UnitCost"]
print(list(df["ProductCost"]))Expected output
[140, 66, 50]Quantity times unit cost is the total product cost.
4. Gross profit
import pandas as pd
df = pd.DataFrame({"Revenue": [240, 120, 90], "ProductCost": [140, 66, 50]})
df["GrossProfit"] = df["Revenue"] - df["ProductCost"]
print(df["GrossProfit"].sum())Expected output
194The sum is gross profit before operating expenses.
5. Order-size labels
import pandas as pd
df = pd.DataFrame({"Revenue": [240, 80, 140, 300]})
df["Size"] = ["Large" if r >= 200 else "Standard" for r in df["Revenue"]]
print(list(df["Size"]))Expected output
['Large', 'Standard', 'Standard', 'Large']The threshold is inclusive and all revenues in this example are observed.
6. Rename a column
import pandas as pd
df = pd.DataFrame({"Store": ["Central", "Kowloon", "Central", "Kowloon"],
"Units": [2, 1, 4, 3], "Price": [120, 80, 35, 60]},
index=["A", "B", "C", "D"])
renamed = df.rename(columns={"Units": "Quantity"})
print(list(renamed.columns))Expected output
['Store', 'Quantity', 'Price']rename returns a table with changed labels.
7. Keep a smaller table
import pandas as pd
df = pd.DataFrame({"Store": ["Central", "Kowloon", "Central", "Kowloon"],
"Units": [2, 1, 4, 3], "Price": [120, 80, 35, 60]},
index=["A", "B", "C", "D"])
compact = df.drop(columns=["Price"])
print(list(compact.columns))
print(list(df.columns))Expected output
['Store', 'Units']
['Store', 'Units', 'Price']The returned result has fewer columns while df retains its original columns.
8. The two largest orders
import pandas as pd
df = pd.DataFrame({"Store": ["Central", "Kowloon", "Central", "Kowloon"],
"Units": [2, 1, 4, 3], "Price": [120, 80, 35, 60]},
index=["A", "B", "C", "D"])
df["Revenue"] = df["Units"] * df["Price"]
ranked = df.sort_values("Revenue", ascending=False)
print(list(ranked.head(2).index))Expected output
['A', 'D']The ranking is based on total order revenue, not unit price.
9. Undefined margins
import pandas as pd
df = pd.DataFrame({"Revenue": [100.0, 0.0, 200.0], "GrossProfit": [40.0, 0.0, 50.0]})
denominator = df["Revenue"].where(df["Revenue"] > 0)
df["Margin"] = df["GrossProfit"] / denominator
print(list(df["Margin"].round(2)))Expected output
[0.4, nan, 0.25]An undefined zero-revenue margin stays missing.
10. Four direction labels
import pandas as pd
df = pd.DataFrame({"Return": [0.02, 0.0, -0.01, None]})
df["Direction"] = "Unknown"
df.loc[df["Return"] > 0, "Direction"] = "Up"
df.loc[df["Return"] == 0, "Direction"] = "Flat"
df.loc[df["Return"] < 0, "Direction"] = "Down"
print(list(df["Direction"]))Expected output
['Up', 'Flat', 'Down', 'Unknown']Explicit cases preserve the difference between zero and unknown.