{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 12: Practice problems (charts with Matplotlib and Seaborn)\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 6, Thursday.\n",
    "\n",
    "Fifteen problems in three levels, on the same ideas and at the same level as the lesson notebook.\n",
    "\n",
    "How to work\n",
    "\n",
    "- Write your code in the cell under each problem and run it with Shift + Enter. Print exactly what the problem asks for.\n",
    "- Most problems ask for two things: print the numbers behind the chart, then draw the chart. Compare what you print with the output under the solution. The chart appears under the cell when you run it; run the solution to see the chart it draws.\n",
    "- A hint and one possible solution are under each problem. Open them only after you have tried.\n",
    "- The problems share the variables of the setup cell, so run that cell first. A problem that continues from another problem needs that problem's cell to be run before it.\n",
    "- The files orders.csv and customers.csv must be in the same folder as this notebook. On the Asiman Data School website they are already there.\n",
    "\n",
    "Tip: Say the question before you draw: \"how do the cities compare in money?\" The question chooses the chart. Then make the small table, look at it, and draw it."
   ],
   "id": "t12p-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "Run this cell first. Every problem below uses what it creates."
   ],
   "id": "t12p-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "customers = pd.read_csv(\"customers.csv\")"
   ],
   "id": "t12p-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Easy"
   ],
   "id": "t12p-003"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 1. The curve of x cubed\n",
    "\n",
    "Make 50 values of `x` from -2 to 2 and `y = x ** 3`. Print the first and the last value of `y` on one line, then draw the curve. Give the chart a title and axis labels."
   ],
   "id": "t12p-004"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-005"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`x = np.linspace(-2, 2, 50)`. The first value is `y[0]`, the last is `y[-1]`: `print(y[0], y[-1])`. Then `plt.plot(x, y)`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "x = np.linspace(-2, 2, 50)\n",
    "y = x ** 3\n",
    "print(y[0], y[-1])\n",
    "\n",
    "plt.plot(x, y)\n",
    "plt.title(\"y = x cubed\")\n",
    "plt.xlabel(\"x\")\n",
    "plt.ylabel(\"y\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "-8.0 8.0\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 2. Orders by category\n",
    "\n",
    "Print the number of orders of every category (`value_counts`), then draw these numbers as a bar chart with Matplotlib. Give the chart a title and axis labels."
   ],
   "id": "t12p-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "Store the result: `counts = df[\"category\"].value_counts()`. The names are `counts.index`, the heights are `counts.values`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "counts = df[\"category\"].value_counts()\n",
    "print(counts)\n",
    "\n",
    "plt.bar(counts.index, counts.values)\n",
    "plt.title(\"Orders by category\")\n",
    "plt.ylabel(\"Orders\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "category\n",
    "Books       74\n",
    "Tech        68\n",
    "Home        56\n",
    "Clothing    54\n",
    "Sports      48\n",
    "Name: count, dtype: int64\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-009"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 3. Orders by city with Seaborn\n",
    "\n",
    "Print the number of orders of every city (`value_counts`), then draw it with `sns.countplot`, the city with the most orders first. Give the chart a title."
   ],
   "id": "t12p-010"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-011"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`sns.countplot(data=df, x=\"city\", order=...)`. The order is the list of cities from `value_counts`: its `.index`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "counts = df[\"city\"].value_counts()\n",
    "print(counts)\n",
    "\n",
    "sns.countplot(data=df, x=\"city\", order=counts.index)\n",
    "plt.title(\"Orders by city\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "city\n",
    "Baku        128\n",
    "Ganja        54\n",
    "Sumqayit     48\n",
    "Quba         30\n",
    "Lankaran     22\n",
    "Shaki        10\n",
    "Name: count, dtype: int64\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Medium"
   ],
   "id": "t12p-013"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 4. Units sold by month\n",
    "\n",
    "Add a column `month` (the month number of `date`). Print the units sold in every month as a list, then draw them as a line chart with markers and with all twelve months on the axis. Give the chart a title and axis labels."
   ],
   "id": "t12p-014"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-015"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df[\"month\"] = pd.to_datetime(df[\"date\"]).dt.month`, then `df.groupby(\"month\")[\"units\"].sum()`. Print it with `.tolist()`. `plt.xticks(range(1, 13))` writes every month.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df[\"month\"] = pd.to_datetime(df[\"date\"]).dt.month\n",
    "units = df.groupby(\"month\")[\"units\"].sum()\n",
    "print(units.tolist())\n",
    "\n",
    "plt.plot(units.index, units.values, marker=\"o\")\n",
    "plt.title(\"Units sold by month\")\n",
    "plt.xlabel(\"Month\")\n",
    "plt.ylabel(\"Units\")\n",
    "plt.xticks(range(1, 13))\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[34, 29, 40, 33, 34, 42, 48, 40, 48, 40, 61, 71]\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 5. The mean price of every city\n",
    "\n",
    "Print the mean price of every city, rounded to 2 decimals and sorted from the smallest to the largest. Then draw it as horizontal bars, so that the largest is at the top. Give the chart a title and axis labels."
   ],
   "id": "t12p-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df.groupby(\"city\")[\"price\"].mean().round(2).sort_values()`. `plt.barh` draws the last value at the top.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "mean_price = df.groupby(\"city\")[\"price\"].mean().round(2).sort_values()\n",
    "print(mean_price)\n",
    "\n",
    "plt.barh(mean_price.index, mean_price.values)\n",
    "plt.title(\"Mean price by city\")\n",
    "plt.xlabel(\"Mean price\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "city\n",
    "Lankaran    34.94\n",
    "Baku        48.84\n",
    "Quba        49.91\n",
    "Ganja       54.11\n",
    "Shaki       56.50\n",
    "Sumqayit    58.64\n",
    "Name: price, dtype: float64\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 6. The ratings of the categories\n",
    "\n",
    "Print the median rating of every category. Then draw the ratings of the categories as box plots with Seaborn. Give the chart a title."
   ],
   "id": "t12p-020"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-021"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df.groupby(\"category\")[\"rating\"].median()` for the numbers, `sns.boxplot(data=df, x=\"category\", y=\"rating\")` for the chart.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "print(df.groupby(\"category\")[\"rating\"].median())\n",
    "\n",
    "sns.boxplot(data=df, x=\"category\", y=\"rating\")\n",
    "plt.title(\"Ratings by category\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "category\n",
    "Books       4.0\n",
    "Clothing    4.5\n",
    "Home        4.0\n",
    "Sports      4.0\n",
    "Tech        4.0\n",
    "Name: rating, dtype: float64\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 7. The money of every city\n",
    "\n",
    "Add a column `total` (price times units). Print the money of every city, rounded to 2 decimals, the largest first. Then draw it with `sns.barplot` and `estimator=\"sum\"`, the bars in the same order. Give the chart a title."
   ],
   "id": "t12p-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "The summary: `df.groupby(\"city\")[\"total\"].sum().round(2).sort_values(ascending=False)`. Its `.index` is the list for `order=`. Add `errorbar=None`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "money = df.groupby(\"city\")[\"total\"].sum().round(2).sort_values(ascending=False)\n",
    "print(money)\n",
    "\n",
    "sns.barplot(data=df, x=\"city\", y=\"total\", estimator=\"sum\", errorbar=None, order=money.index)\n",
    "plt.title(\"Money by city\")\n",
    "plt.ylabel(\"Money\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "city\n",
    "Baku        9093.10\n",
    "Ganja       4213.20\n",
    "Sumqayit    4201.60\n",
    "Quba        1986.82\n",
    "Lankaran    1358.15\n",
    "Shaki        649.64\n",
    "Name: total, dtype: float64\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 8. Price and rating\n",
    "\n",
    "Do expensive products get better ratings? Print the correlations of the columns `price` and `rating`, rounded to 2 decimals (`df[[\"price\", \"rating\"]].corr()`). Then draw a scatter chart of the two columns for all orders, with `alpha=0.5`. Give the chart a title and axis labels."
   ],
   "id": "t12p-026"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`plt.scatter(df[\"price\"], df[\"rating\"], alpha=0.5)`. A number close to 0 and a cloud without direction mean: no.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "print(df[[\"price\", \"rating\"]].corr().round(2))\n",
    "\n",
    "plt.scatter(df[\"price\"], df[\"rating\"], alpha=0.5)\n",
    "plt.title(\"Price and rating\")\n",
    "plt.xlabel(\"Price\")\n",
    "plt.ylabel(\"Rating\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "        price  rating\n",
    "price    1.00    0.05\n",
    "rating   0.05    1.00\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 9. Two cities, month by month\n",
    "\n",
    "**This problem continues from Problem 4**: the table already has the column `month` from your answer there. Print the number of orders of Baku in every month as a list, then the same for Ganja. Then draw both as lines with markers in one chart, with a legend and all twelve months on the axis. Give the chart a title and axis labels."
   ],
   "id": "t12p-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "The rows of one city, then the groups: `df[df[\"city\"] == \"Baku\"].groupby(\"month\").size()`. Two `plt.plot` calls with `label=`, then `plt.legend()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "baku = df[df[\"city\"] == \"Baku\"].groupby(\"month\").size()\n",
    "ganja = df[df[\"city\"] == \"Ganja\"].groupby(\"month\").size()\n",
    "print(baku.tolist())\n",
    "print(ganja.tolist())\n",
    "\n",
    "plt.plot(baku.index, baku.values, marker=\"o\", label=\"Baku\")\n",
    "plt.plot(ganja.index, ganja.values, marker=\"o\", label=\"Ganja\")\n",
    "plt.title(\"Orders by month\")\n",
    "plt.xlabel(\"Month\")\n",
    "plt.ylabel(\"Orders\")\n",
    "plt.xticks(range(1, 13))\n",
    "plt.legend()\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "[10, 9, 12, 6, 8, 9, 15, 7, 14, 14, 5, 19]\n",
    "[3, 2, 3, 10, 2, 4, 4, 6, 3, 6, 5, 6]\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-031"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Medium-Hard"
   ],
   "id": "t12p-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 10. Two histograms side by side\n",
    "\n",
    "Print the highest price of Clothing and the highest price of Home on one line. Then make a figure with two charts next to each other: a histogram of the prices of Clothing and a histogram of the prices of Home, each with 10 bins, a title, and the same limits of the x axis: from 0 to 140."
   ],
   "id": "t12p-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))`. On one chart: `axes[0].hist(...)`, `axes[0].set_title(...)`, `axes[0].set_xlim(0, 140)`. End with `plt.tight_layout()`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "clothing = df[df[\"category\"] == \"Clothing\"][\"price\"]\n",
    "home = df[df[\"category\"] == \"Home\"][\"price\"]\n",
    "print(clothing.max(), home.max())\n",
    "\n",
    "fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))\n",
    "axes[0].hist(clothing, bins=10)\n",
    "axes[0].set_title(\"Prices of Clothing\")\n",
    "axes[0].set_xlim(0, 140)\n",
    "axes[1].hist(home, bins=10)\n",
    "axes[1].set_title(\"Prices of Home\")\n",
    "axes[1].set_xlim(0, 140)\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "129.0 49.9\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 11. A heatmap of ratings\n",
    "\n",
    "Make a table of the mean rating with the cities in the rows and the categories in the columns, rounded to 1 decimal. Print it, then draw it as a heatmap with the numbers in the cells. Give the chart a title."
   ],
   "id": "t12p-036"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-037"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`pd.pivot_table(df, index=\"city\", columns=\"category\", values=\"rating\", aggfunc=\"mean\").round(1)`, then `sns.heatmap(table, annot=True, cmap=\"Blues\")`. Shaki has no order in Home: this cell stays empty.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "table = pd.pivot_table(df, index=\"city\", columns=\"category\", values=\"rating\", aggfunc=\"mean\").round(1)\n",
    "print(table)\n",
    "\n",
    "sns.heatmap(table, annot=True, cmap=\"Blues\")\n",
    "plt.title(\"Mean rating by city and category\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "category  Books  Clothing  Home  Sports  Tech\n",
    "city                                         \n",
    "Baku        4.0       4.1   3.8     4.0   4.1\n",
    "Ganja       4.2       4.3   3.3     4.1   4.2\n",
    "Lankaran    4.1       3.5   4.0     4.3   5.0\n",
    "Quba        4.2       5.0   4.1     4.5   4.2\n",
    "Shaki       4.3       3.0   NaN     4.0   2.5\n",
    "Sumqayit    4.2       4.6   4.4     3.5   3.6\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 12. Cities and gender\n",
    "\n",
    "Join the orders with the customers and store the result in `full` (the default join is right here: an order without a customer has no gender). Print the number of orders by city and gender (`groupby` with two columns and `size`). Then draw the number of orders of every city, split by gender. Give the chart a title."
   ],
   "id": "t12p-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`full = df.merge(customers, on=\"customer\")`, then `full.groupby([\"city\", \"gender\"]).size()`. The chart: `sns.countplot(data=full, x=\"city\", hue=\"gender\")`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "full = df.merge(customers, on=\"customer\")\n",
    "print(full.groupby([\"city\", \"gender\"]).size())\n",
    "\n",
    "sns.countplot(data=full, x=\"city\", hue=\"gender\")\n",
    "plt.title(\"Orders by city and gender\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "city      gender\n",
    "Baku      F         69\n",
    "          M         56\n",
    "Ganja     F         22\n",
    "          M         32\n",
    "Lankaran  F          5\n",
    "          M         17\n",
    "Quba      F         22\n",
    "          M          8\n",
    "Shaki     F          5\n",
    "          M          5\n",
    "Sumqayit  F          5\n",
    "          M         43\n",
    "dtype: int64\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-041"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 13. Money by the year of joining\n",
    "\n",
    "**This problem continues from Problem 12**: the joined table `full` is already there. Add a column `total` (price times units) to `full`. Print the money of the customers who joined in each year (`joined`), rounded to 2 decimals. Then draw it as bars with the years on the axis. Give the chart a title and axis labels."
   ],
   "id": "t12p-042"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-043"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`money = full.groupby(\"joined\")[\"total\"].sum().round(2)`. `plt.bar(money.index, money.values)`, and `plt.xticks(money.index)` writes only the real years.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "full[\"total\"] = full[\"price\"] * full[\"units\"]\n",
    "money = full.groupby(\"joined\")[\"total\"].sum().round(2)\n",
    "print(money)\n",
    "\n",
    "plt.bar(money.index, money.values)\n",
    "plt.title(\"Money by the year the customer joined\")\n",
    "plt.xlabel(\"Year\")\n",
    "plt.ylabel(\"Money\")\n",
    "plt.xticks(money.index)\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "joined\n",
    "2021    3596.13\n",
    "2022    1347.42\n",
    "2023    5154.50\n",
    "2024    6362.77\n",
    "2025    5263.75\n",
    "Name: total, dtype: float64\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 14. Are cheap products sold in larger numbers?\n",
    "\n",
    "Make a table `per_product` with one row for every product: its mean price in the column `price` and the units sold in the column `units`. Print the correlations of this table, rounded to 2 decimals. Then draw the two columns as a scatter chart, the price on the x axis. Give the chart a title and axis labels."
   ],
   "id": "t12p-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`df.groupby(\"product\").agg(price=(\"price\", \"mean\"), units=(\"units\", \"sum\"))`, then `per_product.corr().round(2)`. A negative number means: the higher the price, the fewer units.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "per_product = df.groupby(\"product\").agg(price=(\"price\", \"mean\"), units=(\"units\", \"sum\"))\n",
    "print(per_product.corr().round(2))\n",
    "\n",
    "plt.scatter(per_product[\"price\"], per_product[\"units\"])\n",
    "plt.title(\"Products: price and units sold\")\n",
    "plt.xlabel(\"Mean price\")\n",
    "plt.ylabel(\"Units sold\")\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "**Output**\n",
    "\n",
    "```\n",
    "       price  units\n",
    "price   1.00  -0.59\n",
    "units  -0.59   1.00\n",
    "```\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-047"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Problem 15. Four charts about the customers\n",
    "\n",
    "Make one figure with four charts about the customers of `customers.csv` and their orders. Choose the four questions yourself and write each question as the title of its chart."
   ],
   "id": "t12p-048"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Write your code here"
   ],
   "id": "t12p-049"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<details>\n",
    "<summary><b>Show a hint</b></summary>\n",
    "\n",
    "`fig, axes = plt.subplots(2, 2, figsize=(11, 7))`. A Seaborn chart gets its place with `ax=axes[0, 0]`. For the money of every customer: group the orders by `customer`, then `customers.merge(...)`.\n",
    "\n",
    "</details>\n",
    "\n",
    "<details>\n",
    "<summary><b>Show the solution</b></summary>\n",
    "\n",
    "```python\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "spent = df.groupby(\"customer\")[\"total\"].sum().reset_index()\n",
    "people = customers.merge(spent, on=\"customer\", how=\"left\")\n",
    "\n",
    "fig, axes = plt.subplots(2, 2, figsize=(11, 7))\n",
    "\n",
    "sns.histplot(data=people, x=\"age\", bins=8, ax=axes[0, 0])\n",
    "axes[0, 0].set_title(\"How old are the customers?\")\n",
    "\n",
    "sns.countplot(data=people, x=\"gender\", ax=axes[0, 1])\n",
    "axes[0, 1].set_title(\"How many women and men?\")\n",
    "\n",
    "sns.countplot(data=people, x=\"joined\", ax=axes[1, 0])\n",
    "axes[1, 0].set_title(\"In which year did they join?\")\n",
    "\n",
    "sns.scatterplot(data=people, x=\"age\", y=\"total\", ax=axes[1, 1])\n",
    "axes[1, 1].set_title(\"Do older customers spend more?\")\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "```\n",
    "\n",
    "This solution prints nothing. Run it to see its chart.\n",
    "\n",
    "</details>"
   ],
   "id": "t12p-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When you have finished, compare your solutions with the hidden ones. A different solution that prints the same numbers and draws the same chart is just as good."
   ],
   "id": "t12p-051"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
