Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 4 Solutions: Relationships and a First Streamlit App

Open In Colab

Lab 4 Solutions: Relationships and a First Streamlit App

These are the worked solutions, with outputs. Try the lab yourself first.

The question. The regional manager wants one dashboard to explore the orders, and one answer: which branch and category combination is underperforming, and what should we do about it?

How this lab works

  • Run the cells from top to bottom with Shift + Enter. Replace every ... with your code, then run the check cell under it.

  • Extended track: after Part C, try the ★ challenges.

  • Submit before the next lab session: File → Download → Download .ipynb, plus your qahwa_app.py.

You may use an AI assistant for code. If you do, add a short note at the end: what you asked, what you kept and what you changed.

Loading...
ColumnMeaning
order_id, date, weekday, hourthe order and when it was placed
branch, citywhere
app_user1 if the customer ordered through the loyalty app
drinks, food_itemshow many of each in the order
drink_sar, food_sar, basket_saramounts paid in SAR (basket = drinks + food)

Part A: Crosstabs and pivot tables

A1. A crosstab

Count the orders in each combination of branch and app_user with pd.crosstab. Store it in counts.

Loading...
✅ A1 one row per branch, one column per group
✅ A1 all orders counted

A2. Row percentages

What share of each branch’s orders come from app users? Use normalize="index" and multiply by 100. Store the app-user column (the column 1) in app_share.

branch Al Faisaliyah 21.0 Corniche 20.2 Olaya 15.5 University 75.2 Name: 1, dtype: float64
✅ A2 the University branch has the most app users
✅ A2 percentages

A3. A pivot table

Build a pivot table with one row per branch and the mean of drink_sar, food_sar and basket_sar, plus the share of orders that include food (has_food). Store it in by_branch.

Loading...
✅ A3 four branches
✅ A3 food share is lowest at University

Part B: Relationships

B1. Box plots by branch

Run this cell. Which branch’s baskets are smallest, and which has the most outliers?

<Figure size 700x360 with 1 Axes>

B2. Correlation

Compute the correlation matrix of drinks, food_items and basket_sar. Store it in corr. Which of the two drives the basket more strongly?

Loading...
✅ B2 a 3 x 3 matrix
✅ B2 food items correlate more with the basket than drinks

B3. Do app users spend more?

First compare the mean basket_sar of app users and others overall (store in overall, indexed by app_user), then within each branch with a pivot table (store in within, branches as rows, app_user as columns).

app_user
0    22.53
1    21.03
Name: basket_sar, dtype: float64
Loading...
✅ B3 overall, app users spend less
✅ B3 within every branch, app users spend more

B4. In two sentences: how can both checks above be true? Use your answer to A2.

Answer. Most app-user orders come from the University branch, where every basket is small, so the overall average of app users is pulled down by the branch they order at, not by being app users. Compared within the same branch, app users spend 2.20 to 3.34 SAR more per order: this is Simpson’s paradox, with the branch as the lurking variable.

Part C: A first Streamlit app

A Streamlit app is a Python script: each st. call adds an element to a web page (a title, a slider, a table, a chart), and the script runs again from the top every time the user changes a filter.

C1. Fill in the app

The next cell writes the app to a file, qahwa_app.py. Fill in the five gaps marked ..., run the cell, then run the test cell under it.

Writing qahwa_app.py
✅ C1 the app runs without an error
✅ C1 a revenue-per-order metric
✅ C1 a correlation metric
✅ C1 a pivot table

C2. See it in a browser

Colab cannot show a Streamlit page, so open it in GitHub Codespaces (free with GitHub Education) or on your own computer:

  1. Put qahwa_app.py in a folder, open a terminal there and run pip install streamlit pandas.

  2. Run streamlit run qahwa_app.py; a browser tab opens at http://localhost:8501.

  3. To share it, push the file to a GitHub repository and deploy it on Streamlit Community Cloud (share.streamlit.io): pick the repository and the file, and you get a public link.

The course’s finished version, with more views, is week04/app/app.py in the course repository.

C3. Your recommendation

Use your app: select one branch at a time, and only the food_sar category. Then write three sentences for the manager: which branch × category combination underperforms (with numbers), what you would try, and why the data alone cannot prove the cause.

Recommendation. Food is the weak spot at the University branch: only 17% of its orders include food, against 40% to 47% elsewhere, so food brings in 2.88 SAR per order there against 6.39 to 7.53 SAR in the other branches. I would test a student meal deal (a drink and a sandwich at a set price) on some weeks and not others, and compare food revenue per order. The data cannot tell us why food sells badly there: it may be prices, the menu, the opening hours, or simply customers with smaller budgets, so only such a test can show whether an offer changes their behaviour.

★ Extended challenges

E1. A weekday filter. Add a st.sidebar.multiselect for weekdays to your app and check it still runs with AppTest.

E2. Two correlations, one pair. With the Week 1 sales data, compute the correlation between Iced Latte and Spanish Latte daily units at the Olaya branch, then between their monthly totals. Explain why the sign changes.

E3. An alert. Make your app show st.warning when app users spend more than others in every selected branch but less overall.


chosen_days = st.sidebar.multiselect("Weekdays", days, default=days)
view = view[view["weekday"].isin(chosen_days)]

daily r:   0.25
monthly r: -0.46

Day by day, busy days and promotion days lift both products together (r = +0.25). Month by month, the season dominates: summer pushes iced drinks up and hot drinks down (r = −0.46). Neither product causes the other’s sales; different confounders dominate at different time scales.

st.warning: Simpson's paradox: app users spend more in every branch but less overall.