{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f7581d71",
   "metadata": {},
   "source": [
    "# Lab\n",
    "\n",
    "- Use this assignment to practice the chapter's concepts and coding skills in runnable Python code.\n",
    "- Sign in from the account menu before you start working on the assignment.\n",
    "- Write and run your code directly in the coding cells.\n",
    "- Multiple submissions are allowed. The highest score is kept.\n",
    "\n",
    "<div data-lab-answers-release-at=\"2026-09-17T23:59-05:00\"></div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b88f4749",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:32.713013Z",
     "iopub.status.busy": "2026-09-16T04:40:32.712745Z",
     "iopub.status.idle": "2026-09-16T04:40:32.718838Z",
     "shell.execute_reply": "2026-09-16T04:40:32.718396Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 1: Build a Sales Table\n",
    "# Import pandas as pd, then build a DataFrame from regions and revenues.\n",
    "# Store the DataFrame in a variable named sales_df.\n",
    "# Print exactly:\n",
    "# Rows: 4\n",
    "# Columns: 2\n",
    "regions = [\"East\", \"West\", \"East\", \"South\"]\n",
    "revenues = [1200, 950, 1350, 800]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "098d6318",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:32.721156Z",
     "iopub.status.busy": "2026-09-16T04:40:32.720964Z",
     "iopub.status.idle": "2026-09-16T04:40:32.939550Z",
     "shell.execute_reply": "2026-09-16T04:40:32.939322Z"
    },
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Rows: 4\n",
      "Columns: 2\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import pandas as pd\n",
    "\n",
    "regions = [\"East\", \"West\", \"East\", \"South\"]\n",
    "revenues = [1200, 950, 1350, 800]\n",
    "\n",
    "sales_df = pd.DataFrame({\"region\": regions, \"revenue\": revenues})\n",
    "\n",
    "print(\"Rows:\", sales_df.shape[0])\n",
    "print(\"Columns:\", sales_df.shape[1])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c158c0a1",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:32.940721Z",
     "iopub.status.busy": "2026-09-16T04:40:32.940620Z",
     "iopub.status.idle": "2026-09-16T04:40:32.942388Z",
     "shell.execute_reply": "2026-09-16T04:40:32.942123Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 2: Select Labeled Values\n",
    "# Import pandas as pd, then create a Series from values with labels as its index.\n",
    "# Store the Series in a variable named scores.\n",
    "# Print exactly:\n",
    "# B score: 91\n",
    "# First score: 82\n",
    "values = [82, 91, 76]\n",
    "labels = [\"A\", \"B\", \"C\"]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "68b1f0f2",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:32.943568Z",
     "iopub.status.busy": "2026-09-16T04:40:32.943449Z",
     "iopub.status.idle": "2026-09-16T04:40:32.946234Z",
     "shell.execute_reply": "2026-09-16T04:40:32.945965Z"
    },
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "B score: 91\n",
      "First score: 82\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import pandas as pd\n",
    "\n",
    "values = [82, 91, 76]\n",
    "labels = [\"A\", \"B\", \"C\"]\n",
    "\n",
    "scores = pd.Series(values, index=labels)\n",
    "\n",
    "print(\"B score:\", scores.loc[\"B\"])\n",
    "print(\"First score:\", scores.iloc[0])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "33522031",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:32.949284Z",
     "iopub.status.busy": "2026-09-16T04:40:32.949014Z",
     "iopub.status.idle": "2026-09-16T04:40:32.950824Z",
     "shell.execute_reply": "2026-09-16T04:40:32.950551Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 3: Detect and Fill Missing Sales\n",
    "# Import pandas as pd, then create a Series from sales.\n",
    "# Count missing values with isna(), fill missing values with 0, and total the filled Series.\n",
    "# Print exactly:\n",
    "# Missing sales: 1\n",
    "# Filled total: 215\n",
    "sales = [120, None, 95]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d5ba3b1b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:32.952078Z",
     "iopub.status.busy": "2026-09-16T04:40:32.952000Z",
     "iopub.status.idle": "2026-09-16T04:40:32.955849Z",
     "shell.execute_reply": "2026-09-16T04:40:32.955590Z"
    },
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Missing sales: 1\n",
      "Filled total: 215\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import pandas as pd\n",
    "\n",
    "sales = [120, None, 95]\n",
    "\n",
    "sales_series = pd.Series(sales)\n",
    "missing_sales = int(sales_series.isna().sum())\n",
    "filled_sales = sales_series.fillna(0)\n",
    "\n",
    "print(\"Missing sales:\", missing_sales)\n",
    "print(\"Filled total:\", int(filled_sales.sum()))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "dfd63384",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:32.956854Z",
     "iopub.status.busy": "2026-09-16T04:40:32.956789Z",
     "iopub.status.idle": "2026-09-16T04:40:32.958138Z",
     "shell.execute_reply": "2026-09-16T04:40:32.957978Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 4: Filter and Sort Orders\n",
    "# Import pandas as pd, then create a DataFrame with region and revenue columns.\n",
    "# Keep rows with revenue of at least 1000 and sort from highest to lowest revenue.\n",
    "# Print exactly:\n",
    "# High regions: ['North', 'East']\n",
    "# Top revenue: 1400\n",
    "orders = [[\"East\", 1250], [\"West\", 900], [\"North\", 1400], [\"South\", 700]]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b0bb933f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:32.959045Z",
     "iopub.status.busy": "2026-09-16T04:40:32.958983Z",
     "iopub.status.idle": "2026-09-16T04:40:32.961865Z",
     "shell.execute_reply": "2026-09-16T04:40:32.961693Z"
    },
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "High regions: ['North', 'East']\n",
      "Top revenue: 1400\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import pandas as pd\n",
    "\n",
    "orders = [[\"East\", 1250], [\"West\", 900], [\"North\", 1400], [\"South\", 700]]\n",
    "\n",
    "orders_df = pd.DataFrame(orders, columns=[\"region\", \"revenue\"])\n",
    "high_orders = orders_df[orders_df[\"revenue\"] >= 1000].sort_values(\"revenue\", ascending=False)\n",
    "high_regions = list(high_orders[\"region\"])\n",
    "\n",
    "print(\"High regions:\", high_regions)\n",
    "print(\"Top revenue:\", int(high_orders.iloc[0][\"revenue\"]))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "addc5177",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:32.962784Z",
     "iopub.status.busy": "2026-09-16T04:40:32.962733Z",
     "iopub.status.idle": "2026-09-16T04:40:32.964306Z",
     "shell.execute_reply": "2026-09-16T04:40:32.963994Z"
    },
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Question 5: Group Revenue by Region\n",
    "# Import pandas as pd, then create a DataFrame with region and revenue columns.\n",
    "# Group by region and sum revenue.\n",
    "# Print exactly:\n",
    "# East total: 250\n",
    "# West total: 200\n",
    "sales = [[\"East\", 100], [\"West\", 80], [\"East\", 150], [\"West\", 120], [\"South\", 90]]\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "4da94f19",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-09-16T04:40:32.965336Z",
     "iopub.status.busy": "2026-09-16T04:40:32.965279Z",
     "iopub.status.idle": "2026-09-16T04:40:32.967512Z",
     "shell.execute_reply": "2026-09-16T04:40:32.967347Z"
    },
    "tags": [
     "hide-input",
     "lab-answer"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "East total: 250\n",
      "West total: 200\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import pandas as pd\n",
    "\n",
    "sales = [[\"East\", 100], [\"West\", 80], [\"East\", 150], [\"West\", 120], [\"South\", 90]]\n",
    "\n",
    "sales_df = pd.DataFrame(sales, columns=[\"region\", \"revenue\"])\n",
    "summary = sales_df.groupby(\"region\")[\"revenue\"].sum()\n",
    "\n",
    "print(\"East total:\", int(summary.loc[\"East\"]))\n",
    "print(\"West total:\", int(summary.loc[\"West\"]))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7f9d010",
   "metadata": {},
   "source": [
    "<style>\n",
    ".ch04-lab-grader { max-width: 900px; margin-top: 1rem; }\n",
    ".ch04-lab-feedback-list { display: grid; gap: 0.45rem; margin: 0 0 1rem; }\n",
    ".ch04-lab-feedback-list[hidden] { display: none; }\n",
    ".ch04-lab-feedback-row { border: 1px solid #d8dee4; border-radius: 6px; padding: 0.55rem 0.65rem; }\n",
    ".ch04-lab-feedback-row strong { margin-right: 0.35rem; }\n",
    ".ch04-lab-feedback-row.correct { border-color: #aceebb; background: #dafbe1; color: #116329; }\n",
    ".ch04-lab-feedback-row.incorrect { border-color: #ffcecb; background: #ffebe9; color: #cf222e; }\n",
    ".ch04-lab-actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 0; flex-wrap: wrap; }\n",
    ".ch04-lab-actions button { border: 1px solid #176de8; border-radius: 6px; background: #176de8; color: white; padding: 0.55rem 0.9rem; cursor: pointer; font-weight: 600; }\n",
    ".ch04-lab-actions button.secondary { background: white; color: #176de8; }\n",
    ".ch04-lab-actions.is-locked { opacity: 0.55; }\n",
    ".ch04-lab-actions button:disabled { cursor: not-allowed; opacity: 0.65; }\n",
    ".ch04-lab-result { font-weight: 700; }\n",
    "</style>\n",
    "\n",
    "<div class='ch04-lab-grader' id='ch04-lab-grader'>\n",
    "  <div class='ch04-lab-feedback-list' aria-live='polite' hidden>\n",
    "    <div class='ch04-lab-feedback-row' data-question='q1'><strong>Question 1</strong><span></span></div>\n",
    "    <div class='ch04-lab-feedback-row' data-question='q2'><strong>Question 2</strong><span></span></div>\n",
    "    <div class='ch04-lab-feedback-row' data-question='q3'><strong>Question 3</strong><span></span></div>\n",
    "    <div class='ch04-lab-feedback-row' data-question='q4'><strong>Question 4</strong><span></span></div>\n",
    "    <div class='ch04-lab-feedback-row' data-question='q5'><strong>Question 5</strong><span></span></div>\n",
    "  </div>\n",
    "  <div class='ch04-lab-actions'>\n",
    "    <button type='button' id='ch04-lab-submit' disabled>Submit</button>\n",
    "    <button type='button' class='secondary' id='ch04-lab-reset'>Clear Results</button>\n",
    "    <span class='ch04-lab-result' id='ch04-lab-result' aria-live='polite'></span>\n",
    "  </div>\n",
    "</div>\n",
    "\n",
    "<script>\n",
    "(function () {\n",
    "  var labId = 'ch04-lab';\n",
    "\n",
    "  function getParams() {\n",
    "    var params = new URLSearchParams(window.location.search);\n",
    "    return {\n",
    "      canvas_course_id: params.get('canvas_course_id') || params.get('course_id') || '',\n",
    "      canvas_assignment_id: params.get('canvas_assignment_id') || params.get('assignment_id') || '',\n",
    "      canvas_user_id: params.get('canvas_user_id') || params.get('user_id') || ''\n",
    "    };\n",
    "  }\n",
    "\n",
    "  function loadSessionIdentity(identity, actions, submit, result) {\n",
    "    submit.disabled = true;\n",
    "    actions.classList.add('is-locked');\n",
    "    result.textContent = 'Sign in from the account menu to submit this assignment.';\n",
    "\n",
    "    return fetch('/api/v1/session.php', { credentials: 'same-origin' })\n",
    "      .then(function (response) { return response.ok ? response.json() : null; })\n",
    "      .then(function (payload) {\n",
    "        if (!payload || !payload.authenticated || !payload.identity) return identity;\n",
    "        identity.canvas_user_id = payload.identity.canvas_user_id || identity.canvas_user_id || '';\n",
    "        identity.student_identifier = payload.identity.student_identifier || '';\n",
    "        submit.disabled = false;\n",
    "        actions.classList.remove('is-locked');\n",
    "        result.textContent = payload.identity.display_name ? 'Signed in as ' + payload.identity.display_name + '.' : 'Signed in.';\n",
    "        return identity;\n",
    "      })\n",
    "      .catch(function () { return identity; });\n",
    "  }\n",
    "\n",
    "  function codeFromCell(cell) {\n",
    "    var cm = cell.querySelector('.CodeMirror');\n",
    "    if (cm && cm.CodeMirror && typeof cm.CodeMirror.getValue === 'function') return cm.CodeMirror.getValue();\n",
    "    var cmContent = cell.querySelector('.cm-content');\n",
    "    if (cmContent && cmContent.cmView && cmContent.cmView.view) return cmContent.cmView.view.state.doc.toString();\n",
    "    var textarea = cell.querySelector('textarea');\n",
    "    if (textarea) return textarea.value;\n",
    "    var pre = cell.querySelector('.cell_input pre');\n",
    "    return pre ? pre.textContent : '';\n",
    "  }\n",
    "\n",
    "  function collectCodeCells() {\n",
    "    var cells = Array.prototype.slice.call(document.querySelectorAll('div.cell.tag_thebe-interactive')).slice(0, 5);\n",
    "    var code = {};\n",
    "    cells.forEach(function (cell, index) {\n",
    "      code['q' + (index + 1)] = codeFromCell(cell);\n",
    "    });\n",
    "    return code;\n",
    "  }\n",
    "\n",
    "  function applyFeedback(grader, feedback) {\n",
    "    var list = grader.querySelector('.ch04-lab-feedback-list');\n",
    "    list.hidden = false;\n",
    "    ['q1', 'q2', 'q3', 'q4', 'q5'].forEach(function (question) {\n",
    "      var row = grader.querySelector('[data-question=' + question + ']');\n",
    "      var message = row.querySelector('span');\n",
    "      var item = feedback[question];\n",
    "      row.className = 'ch04-lab-feedback-row';\n",
    "      if (!item) return;\n",
    "      message.textContent = item.message + ' (' + item.score + ' / ' + item.max_score + ')';\n",
    "      row.classList.add(item.correct ? 'correct' : 'incorrect');\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function clearFeedback(grader) {\n",
    "    var list = grader.querySelector('.ch04-lab-feedback-list');\n",
    "    list.hidden = true;\n",
    "    grader.querySelectorAll('.ch04-lab-feedback-row').forEach(function (row) {\n",
    "      row.className = 'ch04-lab-feedback-row';\n",
    "      var message = row.querySelector('span');\n",
    "      if (message) message.textContent = '';\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function saveAttempt(payload) {\n",
    "    return fetch('/api/v1/lab-attempts.php', {\n",
    "      method: 'POST',\n",
    "      headers: { 'Content-Type': 'application/json' },\n",
    "      credentials: 'same-origin',\n",
    "      body: JSON.stringify(payload)\n",
    "    }).then(function (response) {\n",
    "      return response.text().then(function (text) {\n",
    "        var payload = text ? JSON.parse(text) : null;\n",
    "        if (!payload || !response.ok || !payload.ok) {\n",
    "          throw new Error((payload && (payload.message || payload.error)) || 'Submission API is unavailable.');\n",
    "        }\n",
    "        return payload;\n",
    "      });\n",
    "    });\n",
    "  }\n",
    "\n",
    "  function initLabGrader() {\n",
    "    var grader = document.getElementById('ch04-lab-grader');\n",
    "    if (!grader || grader.dataset.ready === 'true') return;\n",
    "    grader.dataset.ready = 'true';\n",
    "\n",
    "    var identity = getParams();\n",
    "    var actions = grader.querySelector('.ch04-lab-actions');\n",
    "    var result = document.getElementById('ch04-lab-result');\n",
    "    var submit = document.getElementById('ch04-lab-submit');\n",
    "    var reset = document.getElementById('ch04-lab-reset');\n",
    "\n",
    "    loadSessionIdentity(identity, actions, submit, result);\n",
    "\n",
    "    submit.addEventListener('click', function () {\n",
    "      clearFeedback(grader);\n",
    "      submit.disabled = true;\n",
    "      result.textContent = 'Submitting code.';\n",
    "\n",
    "      saveAttempt({\n",
    "        lab_id: labId,\n",
    "        code: collectCodeCells(),\n",
    "        canvas_course_id: identity.canvas_course_id,\n",
    "        canvas_assignment_id: identity.canvas_assignment_id,\n",
    "        canvas_user_id: identity.canvas_user_id\n",
    "      })\n",
    "        .then(function (payload) {\n",
    "          var best = (payload.best_score === null || typeof payload.best_score === 'undefined') ? payload.score : payload.best_score;\n",
    "          var attempt = (payload.attempt_count === null || typeof payload.attempt_count === 'undefined') ? '' : ' Attempt ' + payload.attempt_count + '.';\n",
    "          applyFeedback(grader, payload.feedback || {});\n",
    "          result.textContent = 'Submission saved.' + attempt + ' Score: ' + payload.score + ' / ' + payload.max_score + '. Best score: ' + best + ' / ' + payload.max_score + '. Canvas sync: ' + payload.canvas_sync_status + '.';\n",
    "        })\n",
    "        .catch(function (error) {\n",
    "          result.textContent = 'Could not save this attempt: ' + error.message;\n",
    "        })\n",
    "        .finally(function () {\n",
    "          submit.disabled = false;\n",
    "        });\n",
    "    });\n",
    "\n",
    "    reset.addEventListener('click', function () {\n",
    "      clearFeedback(grader);\n",
    "      result.textContent = '';\n",
    "    });\n",
    "  }\n",
    "\n",
    "  if (document.readyState === 'loading') {\n",
    "    document.addEventListener('DOMContentLoaded', initLabGrader);\n",
    "  } else {\n",
    "    initLabGrader();\n",
    "  }\n",
    "})();\n",
    "</script>\n"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
