{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 11: Pandas data cleaning and wrangling\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 6, Tuesday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. When a cell reads input, a small box appears: type the values there and press Enter. The practice problems are in a separate notebook, topic-11-practice.ipynb.\n",
    "\n",
    "Inside a part the cells continue from each other: a cell uses the variables of the cells above it. To start in the middle, run the part from its first cell.\n",
    "\n",
    "This notebook reads the files orders.csv and customers.csv. Put them into the same folder as the notebook. On the Asiman Data School website they are already there.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. Choosing rows with a condition\n",
    "2. Missing values\n",
    "3. Duplicates\n",
    "4. Repairing types\n",
    "5. Cleaning text\n",
    "6. Summaries by group\n",
    "7. Joining tables\n",
    "8. From the file to the answer\n",
    "9. Common mistakes\n",
    "10. Solved problems (easy to medium-hard)\n",
    "11. Practice problems (try them yourself) (in topic-11-practice.ipynb)\n",
    "12. Check yourself (on the website)\n",
    "13. Quick summary"
   ],
   "id": "t11-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: cleaning and wrangling data\n",
    "\n",
    "What matters most in this lesson. Four things matter most today: choosing rows with a condition, `df[df[\"price\"] > 100]`; finding gaps with `isna().sum()` and deciding whether to remove or fill them; summaries by group with `groupby`; and joining two tables with `merge`. With these four you can answer most questions about a table.\n",
    "\n",
    "Duplicates, types and text are the checks you run before you trust a table: one look at each is enough today, and you will repeat them with every new file. `pivot_table` and `concat` are a first look. There are 15 solved problems. Start with Level 1 and come back for the rest.\n",
    "\n",
    "A beginner-friendly guide to the daily work with tables in pandas. Real data is never ready: values are missing, numbers are stored as text, names are written in three ways, and the answer you need is spread over two files. This guide shows how to choose rows with a condition, how to find and repair missing values, duplicates, wrong types and messy text, how to summarise a table by groups, and how to join two tables. It starts from the simplest examples and gets harder step by step. Then it walks through 15 solved problems from easy to medium-hard. At the end there are practice problems.\n",
    "\n",
    "You should already know the last lesson: reading a file, `head`, `info`, choosing columns, `loc` and `iloc`, sorting and making a new column.\n",
    "\n",
    "The data files. The examples use the same file as the last lesson, `orders.csv`: 300 orders of a small online shop in 2025. For joining tables there is a second file, `customers.csv`: one row for every customer. Put both files into the same folder as your notebook.\n",
    "\n",
    "## 1. Choosing rows with a condition\n",
    "\n",
    "In the NumPy lesson a condition on an array gave a mask of `True` and `False`, and the mask chose the elements. A column of a table works in the same way, and the mask chooses rows.\n",
    "\n",
    "### 1.1 A condition gives a mask\n",
    "\n",
    "Change it and run: change 100 to 50. How many orders are above 50?"
   ],
   "id": "t11-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "expensive = df[\"price\"] > 100\n",
    "print(expensive.head())\n",
    "print(expensive.sum())"
   ],
   "id": "t11-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The comparison is done for every row. `True` counts as 1, so `sum` counts the rows where the condition holds: 18 orders have a price above 100.\n",
    "\n",
    "### 1.2 The mask chooses the rows\n",
    "\n",
    "Change it and run: print the orders with exactly 5 units."
   ],
   "id": "t11-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[df[\"price\"] > 200])"
   ],
   "id": "t11-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Read `df[df[\"price\"] > 200]` as: \"the rows of `df` where the price is above 200\". The rows keep their labels.\n",
    "\n",
    "### 1.3 Conditions with text\n",
    "\n",
    "Change it and run: write `\"shaki\"` with a small letter. No row is found."
   ],
   "id": "t11-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "shaki = df[df[\"city\"] == \"Shaki\"]\n",
    "print(len(shaki))\n",
    "print(shaki.head(3))"
   ],
   "id": "t11-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`==` compares for equality. Text must match exactly: `\"shaki\"` with a small letter finds nothing.\n",
    "\n",
    "### 1.4 Two conditions: `&`, `|` and `~`\n",
    "\n",
    "As with NumPy masks: `&` means \"and\", `|` means \"or\", `~` means \"not\", and every condition needs its own parentheses.\n",
    "\n",
    "Change it and run: count the orders of Ganja in the category Books."
   ],
   "id": "t11-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "baku_tech = df[(df[\"city\"] == \"Baku\") & (df[\"category\"] == \"Tech\")]\n",
    "print(len(baku_tech))\n",
    "\n",
    "cheap_or_many = df[(df[\"price\"] < 8) | (df[\"units\"] == 5)]\n",
    "print(len(cheap_or_many))\n",
    "\n",
    "not_baku = df[~(df[\"city\"] == \"Baku\")]\n",
    "print(len(not_baku))"
   ],
   "id": "t11-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.5 One of several values: `isin`\n",
    "\n",
    "Change it and run: add `\"Lankaran\"` to the list."
   ],
   "id": "t11-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "small_cities = df[df[\"city\"].isin([\"Shaki\", \"Quba\"])]\n",
    "print(len(small_cities))\n",
    "print(small_cities[\"city\"].value_counts())"
   ],
   "id": "t11-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`isin` takes a list and is `True` where the value is one of the list. It replaces a long chain of `|`.\n",
    "\n",
    "### 1.6 Between two numbers: `between`\n",
    "\n",
    "Change it and run: count the prices from 10 to 20."
   ],
   "id": "t11-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "middle = df[df[\"price\"].between(50, 100)]\n",
    "print(len(middle))\n",
    "print(middle[\"price\"].min(), middle[\"price\"].max())"
   ],
   "id": "t11-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`between(50, 100)` includes both ends. It means the same as `(df[\"price\"] >= 50) & (df[\"price\"] <= 100)`.\n",
    "\n",
    "### 1.7 A piece of text: `str.contains`\n",
    "\n",
    "Change it and run: look for `\"mat\"` instead of `\"book\"`."
   ],
   "id": "t11-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "books = df[df[\"product\"].str.contains(\"book\")]\n",
    "print(books[\"product\"].unique().tolist())\n",
    "print(len(books))"
   ],
   "id": "t11-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`str.contains(\"book\")` is `True` where the text has \"book\" somewhere inside: Cookbook and Textbook.\n",
    "\n",
    "### 1.8 Rows by a condition, columns by name: `loc`\n",
    "\n",
    "Change it and run: show the columns `date` and `city` of the same rows."
   ],
   "id": "t11-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.loc[df[\"units\"] == 5, [\"customer\", \"product\", \"units\"]])"
   ],
   "id": "t11-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A mask can stand in the row place of `loc`. After the comma come the columns you want to see.\n",
    "\n",
    "### 1.9 Summaries of the chosen rows\n",
    "\n",
    "Change it and run: do the same for Sumqayit."
   ],
   "id": "t11-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "baku = df[df[\"city\"] == \"Baku\"]\n",
    "ganja = df[df[\"city\"] == \"Ganja\"]\n",
    "print(len(baku), round(baku[\"price\"].mean(), 2))\n",
    "print(len(ganja), round(ganja[\"price\"].mean(), 2))"
   ],
   "id": "t11-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Filtering first and then summarising answers questions like \"what is the average price in Baku?\".\n",
    "\n",
    "### 1.10 Changing values where a condition holds\n",
    "\n",
    "Change it and run: call the orders with 4 or more units `\"large\"`."
   ],
   "id": "t11-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"size\"] = \"small\"\n",
    "df.loc[df[\"units\"] >= 3, \"size\"] = \"large\"\n",
    "print(df[[\"product\", \"units\", \"size\"]].head(4))\n",
    "print(df[\"size\"].value_counts())"
   ],
   "id": "t11-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`df.loc[mask, column] = value` changes only the rows where the mask is `True`.\n",
    "\n",
    "| You write | You get |\n",
    "| --- | --- |\n",
    "| `df[\"price\"] > 100` | a mask: `True` or `False` for every row |\n",
    "| `df[df[\"price\"] > 100]` | the rows where the condition holds |\n",
    "| `(a) & (b)`, `(a) \\| (b)`, `~(a)` | and, or, not |\n",
    "| `df[\"city\"].isin([\"Shaki\", \"Quba\"])` | the value is one of the list |\n",
    "| `df[\"price\"].between(50, 100)` | from 50 to 100, both included |\n",
    "| `df[\"product\"].str.contains(\"book\")` | the text has this piece inside |\n",
    "| `df.loc[mask, [\"customer\", \"units\"]]` | the chosen rows, only these columns |\n",
    "| `df.loc[mask, \"size\"] = \"large\"` | changes the chosen rows |\n",
    "\n",
    "## 2. Missing values\n",
    "\n",
    "### 2.1 Finding them\n",
    "\n",
    "Change it and run: print `df.notna().sum()`: the number of values that are there."
   ],
   "id": "t11-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.isna().sum())"
   ],
   "id": "t11-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`isna()` gives `True` where a value is missing, and `sum` counts the `True` values of every column. Two columns have gaps: `city` (8) and `rating` (36).\n",
    "\n",
    "### 2.2 The rows with a missing value\n",
    "\n",
    "Change it and run: print the rows where the rating is missing: only the first 5."
   ],
   "id": "t11-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[df[\"city\"].isna()])\n",
    "print(df[\"rating\"].notna().sum())"
   ],
   "id": "t11-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`isna()` is a mask like any other, so it chooses rows. `notna()` is the opposite: 264 orders have a rating.\n",
    "\n",
    "### 2.3 Why not `== NaN`?"
   ],
   "id": "t11-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(len(df[df[\"rating\"] == float(\"nan\")]))\n",
    "print(len(df[df[\"rating\"].isna()]))"
   ],
   "id": "t11-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A missing value is not equal to anything, not even to another missing value. A comparison with `==` never finds it. Always use `isna()`.\n",
    "\n",
    "### 2.4 Way 1: remove the rows, `dropna`\n",
    "\n",
    "Change it and run: check only the column `rating`: `df.dropna(subset=[\"rating\"])`."
   ],
   "id": "t11-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.shape)\n",
    "print(df.dropna().shape)\n",
    "print(df.dropna(subset=[\"city\"]).shape)"
   ],
   "id": "t11-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`dropna()` removes every row that has a gap anywhere: 42 rows are lost. With `subset` only the named columns are checked: only the 8 rows without a city go. `dropna` gives a new table, as most methods do.\n",
    "\n",
    "### 2.5 Way 2: fill the gaps, `fillna`\n",
    "\n",
    "A missing text can get a clear word:\n",
    "\n",
    "Change it and run: fill with `\"No city\"` instead."
   ],
   "id": "t11-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"city\"] = df[\"city\"].fillna(\"Unknown\")\n",
    "print(df[\"city\"].value_counts())"
   ],
   "id": "t11-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`fillna` gives a new column, so the result is stored back into `df[\"city\"]`. Now all 300 orders are counted.\n",
    "\n",
    "A missing number is often filled with the median or the mean of the column:\n",
    "\n",
    "Change it and run: fill with the mean instead of the median. What is the mean of the column after it?"
   ],
   "id": "t11-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "middle = df[\"rating\"].median()\n",
    "print(middle)\n",
    "df[\"rating\"] = df[\"rating\"].fillna(middle)\n",
    "print(df[\"rating\"].isna().sum())\n",
    "print(round(df[\"rating\"].mean(), 2))"
   ],
   "id": "t11-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The median of the ratings is 4.0, and the 36 gaps get this value. No gap is left.\n",
    "\n",
    "### 2.6 Remove or fill?\n",
    "\n",
    "| Situation | A good choice |\n",
    "| --- | --- |\n",
    "| Few rows have gaps, and you have many rows | remove them: `dropna(subset=[...])` |\n",
    "| The column is text | fill with a word: `fillna(\"Unknown\")` |\n",
    "| The column is a number | fill with the median (or the mean) |\n",
    "| The gap itself is the information (\"gave no rating\") | keep it, and remember that summaries skip it |\n",
    "| Most values of a column are missing | remove the column: `drop(columns=[...])` |\n",
    "\n",
    "There is no rule that is always right. Filling changes the data, so say what you did.\n",
    "\n",
    "## 3. Duplicates\n",
    "\n",
    "Sometimes the same row is in a file twice, for example because a form was sent two times.\n",
    "\n",
    "### 3.1 Finding and removing them\n",
    "\n",
    "Change it and run: change the last city from Shaki to Ganja. Now there are two duplicates."
   ],
   "id": "t11-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "visits = pd.DataFrame({\n",
    "    \"name\": [\"Aylin\", \"Murad\", \"Aylin\", \"Leyla\", \"Murad\"],\n",
    "    \"city\": [\"Baku\", \"Ganja\", \"Baku\", \"Baku\", \"Shaki\"],\n",
    "})\n",
    "print(visits.duplicated())\n",
    "print(visits.duplicated().sum())\n",
    "print(visits.drop_duplicates())"
   ],
   "id": "t11-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`duplicated()` marks a row as `True` when the same row appeared before it. Row 2 repeats row 0. Row 4 is not a duplicate: the name is the same, but the city is different. `drop_duplicates()` keeps the first of the equal rows.\n",
    "\n",
    "### 3.2 Duplicates in some columns only\n",
    "\n",
    "Change it and run: compare only the column `city`."
   ],
   "id": "t11-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(visits.drop_duplicates(subset=[\"name\"]))"
   ],
   "id": "t11-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `subset` only these columns are compared: every name stays once, with its first row.\n",
    "\n",
    "### 3.3 The orders\n",
    "\n",
    "Change it and run: keep the first order of every city instead."
   ],
   "id": "t11-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.duplicated().sum())\n",
    "\n",
    "first_orders = df.drop_duplicates(subset=[\"customer\"])\n",
    "print(len(first_orders))\n",
    "print(first_orders[[\"date\", \"customer\", \"product\"]].head(3))"
   ],
   "id": "t11-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The file has no repeated rows. `drop_duplicates(subset=[\"customer\"])` has another use here: it keeps the first order of each of the 40 customers.\n",
    "\n",
    "## 4. Repairing types\n",
    "\n",
    "A column of numbers that was read as text cannot be added up or compared. The type is the first thing to check, with `dtypes` or `info()`.\n",
    "\n",
    "### 4.1 A small messy table\n",
    "\n",
    "This table is like many real files: typed by hand, with mistakes."
   ],
   "id": "t11-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "raw = pd.DataFrame({\n",
    "    \"name\": [\" aylin\", \"MURAD \", \"Leyla\", \"leyla\", \"Kamran\"],\n",
    "    \"city\": [\"baku\", \"Baku \", \"GANJA\", \"Ganja\", \"baku\"],\n",
    "    \"age\": [\"20\", \"25\", \"twenty-two\", \"22\", \"30\"],\n",
    "    \"paid\": [\"15.5 AZN\", \"20 AZN\", \"n/a\", \"18.0 AZN\", \"25.5 AZN\"],\n",
    "})\n",
    "print(raw)\n",
    "print(raw.dtypes)"
   ],
   "id": "t11-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every column is text, also `age`. This part repairs `age`, and Part 5 repairs the text columns.\n",
    "\n",
    "### 4.2 `pd.to_numeric`\n",
    "\n",
    "```python\n",
    "raw = pd.DataFrame({\n",
    "    \"name\": [\" aylin\", \"MURAD \", \"Leyla\", \"leyla\", \"Kamran\"],\n",
    "    \"age\": [\"20\", \"25\", \"twenty-two\", \"22\", \"30\"],\n",
    "})\n",
    "raw[\"age\"] = pd.to_numeric(raw[\"age\"])\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: Unable to parse string \"twenty-two\" at position 2\n",
    "```\n",
    "\n",
    "One value is not a number, so the conversion stops. With `errors=\"coerce\"` such values become missing values instead:\n",
    "\n",
    "Change it and run: change `\"twenty-two\"` to `\"22\"`. No gap is left."
   ],
   "id": "t11-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raw = pd.DataFrame({\n",
    "    \"name\": [\" aylin\", \"MURAD \", \"Leyla\", \"leyla\", \"Kamran\"],\n",
    "    \"age\": [\"20\", \"25\", \"twenty-two\", \"22\", \"30\"],\n",
    "})\n",
    "raw[\"age\"] = pd.to_numeric(raw[\"age\"], errors=\"coerce\")\n",
    "print(raw)\n",
    "print(raw[\"age\"].dtype)\n",
    "print(raw[\"age\"].mean())"
   ],
   "id": "t11-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now `age` is a number column with one gap, and the mean can be calculated. The gap is a job for Part 2.\n",
    "\n",
    "### 4.3 `astype`: when every value fits\n",
    "\n",
    "Change it and run: fill the gap with 0 instead of the median."
   ],
   "id": "t11-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raw = pd.DataFrame({\"age\": [\"20\", \"25\", \"twenty-two\", \"22\", \"30\"]})\n",
    "raw[\"age\"] = pd.to_numeric(raw[\"age\"], errors=\"coerce\")\n",
    "raw[\"age\"] = raw[\"age\"].fillna(raw[\"age\"].median())\n",
    "raw[\"age\"] = raw[\"age\"].astype(int)\n",
    "print(raw[\"age\"].tolist())"
   ],
   "id": "t11-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A column with a gap is stored as decimals. After the gap is filled, `astype(int)` makes whole numbers again. `astype` is strict: it works only when every value can be converted.\n",
    "\n",
    "### 4.4 Dates: `pd.to_datetime`\n",
    "\n",
    "Change it and run: print the three weekdays with the most orders."
   ],
   "id": "t11-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"date\"] = pd.to_datetime(df[\"date\"])\n",
    "df[\"month\"] = df[\"date\"].dt.month\n",
    "df[\"weekday\"] = df[\"date\"].dt.day_name()\n",
    "print(df[[\"date\", \"month\", \"weekday\"]].head(3))\n",
    "print(df[\"month\"].value_counts().head(3))"
   ],
   "id": "t11-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`pd.to_datetime` turns text into real dates. Real dates have the `.dt` tools: `dt.month`, `dt.day`, `dt.year`, `dt.day_name()`. With a `month` column you can count and group by month: December was the busiest month.\n",
    "\n",
    "### 4.5 Columns of one kind: `select_dtypes`\n",
    "\n",
    "Change it and run: print the largest value of every number column."
   ],
   "id": "t11-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "numbers = df.select_dtypes(include=\"number\")\n",
    "print(numbers.columns.tolist())\n",
    "print(numbers.mean().round(2))\n",
    "\n",
    "others = df.select_dtypes(exclude=\"number\")\n",
    "print(others.columns.tolist())"
   ],
   "id": "t11-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`select_dtypes(include=\"number\")` keeps only the number columns, `exclude=\"number\"` keeps the rest. It is handy before a calculation that makes sense only for numbers.\n",
    "\n",
    "| You write | What it does |\n",
    "| --- | --- |\n",
    "| `df.dtypes` | shows the type of every column |\n",
    "| `pd.to_numeric(column, errors=\"coerce\")` | text to numbers; what is not a number becomes missing |\n",
    "| `column.astype(int)` | changes the type; every value must fit |\n",
    "| `pd.to_datetime(column)` | text to real dates |\n",
    "| `column.dt.month`, `column.dt.day_name()` | parts of a date |\n",
    "| `df.select_dtypes(include=\"number\")` | only the number columns |\n",
    "\n",
    "## 5. Cleaning text\n",
    "\n",
    "For a computer, `\"baku\"`, `\"Baku \"` and `\"Baku\"` are three different cities. Text columns have their own tools, reached with `.str`.\n",
    "\n",
    "### 5.1 The problem"
   ],
   "id": "t11-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "raw = pd.DataFrame({\n",
    "    \"name\": [\" aylin\", \"MURAD \", \"Leyla\", \"leyla\", \"Kamran\"],\n",
    "    \"city\": [\"baku\", \"Baku \", \"GANJA\", \"Ganja\", \"baku\"],\n",
    "})\n",
    "print(raw[\"city\"].value_counts())"
   ],
   "id": "t11-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Two cities are counted as four.\n",
    "\n",
    "### 5.2 `strip`, `lower`, `upper`, `title`\n",
    "\n",
    "Change it and run: use `.str.upper()` instead of `.str.title()`."
   ],
   "id": "t11-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raw[\"city\"] = raw[\"city\"].str.strip().str.title()\n",
    "raw[\"name\"] = raw[\"name\"].str.strip().str.title()\n",
    "print(raw)\n",
    "print(raw[\"city\"].value_counts())"
   ],
   "id": "t11-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`str.strip()` removes the spaces at both ends, and `str.title()` writes every word with a capital first letter. The methods are the string methods you know, done for the whole column. Now the cities are counted correctly, and the two rows of Leyla have become equal, so `drop_duplicates` could find them.\n",
    "\n",
    "### 5.3 `str.replace`, then a number\n",
    "\n",
    "Change it and run: change `\"n/a\"` to `\"12 AZN\"`. The sum grows."
   ],
   "id": "t11-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raw = pd.DataFrame({\"paid\": [\"15.5 AZN\", \"20 AZN\", \"n/a\", \"18.0 AZN\", \"25.5 AZN\"]})\n",
    "raw[\"paid\"] = raw[\"paid\"].str.replace(\" AZN\", \"\")\n",
    "print(raw[\"paid\"].tolist())\n",
    "\n",
    "raw[\"paid\"] = pd.to_numeric(raw[\"paid\"], errors=\"coerce\")\n",
    "print(raw[\"paid\"].tolist())\n",
    "print(raw[\"paid\"].sum())"
   ],
   "id": "t11-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First the text \" AZN\" is removed, then `to_numeric` makes numbers, and \"n/a\" becomes a missing value. Cleaning is often a chain of such small steps.\n",
    "\n",
    "| You write | What it does |\n",
    "| --- | --- |\n",
    "| `column.str.strip()` | removes spaces at both ends |\n",
    "| `column.str.lower()`, `.str.upper()`, `.str.title()` | changes the letters |\n",
    "| `column.str.replace(\" AZN\", \"\")` | replaces a piece of text |\n",
    "| `column.str.contains(\"book\")` | `True` where the piece is inside |\n",
    "| `column.str.len()` | the length of every text |\n",
    "\n",
    "## 6. Summaries by group\n",
    "\n",
    "\"The average price\" is one number. \"The average price of every category\" needs groups. `groupby` does three things: it splits the rows into groups, calculates a summary for every group, and puts the results together.\n",
    "\n",
    "```\n",
    "   the rows                 split into groups           one result for every group\n",
    "\n",
    "   category  price          Books:  24.90, 12.50        Books   18.70\n",
    "   Books     24.90    ->                          ->\n",
    "   Tech      89.90          Tech:   89.90, 45.00        Tech    67.45\n",
    "   Books     12.50\n",
    "   Tech      45.00\n",
    "```\n",
    "\n",
    "### 6.1 One column, one summary\n",
    "\n",
    "Change it and run: group by `city` instead of `category`."
   ],
   "id": "t11-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.groupby(\"category\")[\"price\"].mean())"
   ],
   "id": "t11-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Read it from left to right: group by `category`, take the column `price`, calculate the mean. The result is a Series, and the groups are its labels.\n",
    "\n",
    "### 6.2 Other summaries\n",
    "\n",
    "Change it and run: print the largest price of every category."
   ],
   "id": "t11-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.groupby(\"city\")[\"units\"].sum())\n",
    "print(df.groupby(\"category\")[\"rating\"].count())\n",
    "print(df.groupby(\"category\").size())"
   ],
   "id": "t11-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`sum`, `mean`, `median`, `min`, `max` and `count` all work. `count` counts the values that are not missing, and `size` counts all rows of a group. Notice the first result: the 8 orders without a city are in no group.\n",
    "\n",
    "### 6.3 Group, then sort\n",
    "\n",
    "Change it and run: sort from the smallest to the largest."
   ],
   "id": "t11-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "revenue = df.groupby(\"category\")[\"total\"].sum()\n",
    "print(revenue.sort_values(ascending=False))"
   ],
   "id": "t11-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The money of every category, the largest first. A new column, a group and a sort: this chain answers most business questions.\n",
    "\n",
    "### 6.4 Several summaries at once: `agg`\n",
    "\n",
    "Change it and run: add `\"min\"` to the list."
   ],
   "id": "t11-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.groupby(\"category\")[\"price\"].agg([\"count\", \"mean\", \"max\"]).round(2))"
   ],
   "id": "t11-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A list of names gives one column for every summary.\n",
    "\n",
    "### 6.5 Different columns, different summaries\n",
    "\n",
    "Change it and run: use `\"max\"` for the rating."
   ],
   "id": "t11-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "report = df.groupby(\"city\").agg({\"units\": \"sum\", \"total\": \"sum\", \"rating\": \"mean\"})\n",
    "print(report.round(2))"
   ],
   "id": "t11-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A dictionary says which summary to use for which column.\n",
    "\n",
    "### 6.6 Groups by two columns\n",
    "\n",
    "Change it and run: print the number of orders in Ganja in the category Books."
   ],
   "id": "t11-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "counts = df.groupby([\"city\", \"category\"]).size()\n",
    "print(counts.head(7))\n",
    "print(counts[\"Baku\"][\"Tech\"])"
   ],
   "id": "t11-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Every pair of city and category is one group. The result has two levels of labels.\n",
    "\n",
    "### 6.7 Back to a normal table: `reset_index`\n",
    "\n",
    "Change it and run: show the three pairs with the fewest orders."
   ],
   "id": "t11-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "table = df.groupby([\"city\", \"category\"]).size().reset_index(name=\"orders\")\n",
    "print(table.head(4))\n",
    "print(table.sort_values(\"orders\", ascending=False).head(2))"
   ],
   "id": "t11-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`reset_index` turns the group labels into normal columns, so the result can be sorted, filtered and saved like any table.\n",
    "\n",
    "### 6.8 Groups by month\n",
    "\n",
    "Change it and run: add `\"mean\"` to the list of summaries."
   ],
   "id": "t11-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "df[\"month\"] = pd.to_datetime(df[\"date\"]).dt.month\n",
    "monthly = df.groupby(\"month\")[\"total\"].agg([\"count\", \"sum\"])\n",
    "print(monthly.round(2))"
   ],
   "id": "t11-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The number of orders and the money of every month. The end of the year is the strongest.\n",
    "\n",
    "### 6.9 A table of two groups: `pivot_table`\n",
    "\n",
    "Change it and run: put the average price into the cells: `values=\"price\", aggfunc=\"mean\"`, and round to 1 decimal."
   ],
   "id": "t11-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "table = df.pivot_table(index=\"city\", columns=\"category\", values=\"units\", aggfunc=\"sum\")\n",
    "print(table)"
   ],
   "id": "t11-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`pivot_table` puts one group into the rows and another into the columns. Here every cell is the number of units sold in that city and category.\n",
    "\n",
    "### 6.10 Filtering the groups\n",
    "\n",
    "Change it and run: show the customers with at least 10 orders."
   ],
   "id": "t11-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "orders = df.groupby(\"customer\").size()\n",
    "loyal = orders[orders >= 15]\n",
    "print(loyal.sort_values(ascending=False))"
   ],
   "id": "t11-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result of a `groupby` is a Series, so a condition filters it like any other Series: the customers with at least 15 orders.\n",
    "\n",
    "| You write | You get |\n",
    "| --- | --- |\n",
    "| `df.groupby(\"category\")[\"price\"].mean()` | the mean price of every category |\n",
    "| `df.groupby(\"city\").size()` | the number of rows of every city |\n",
    "| `.agg([\"count\", \"mean\", \"max\"])` | several summaries at once |\n",
    "| `.agg({\"units\": \"sum\", \"rating\": \"mean\"})` | a summary for each column |\n",
    "| `df.groupby([\"city\", \"category\"])` | groups by two columns |\n",
    "| `.reset_index()` | the group labels become normal columns |\n",
    "| `df.pivot_table(index=, columns=, values=, aggfunc=)` | one group in the rows, one in the columns |\n",
    "\n",
    "## 7. Joining tables\n",
    "\n",
    "Data about one thing often lives in two files. The orders say who bought something. How old the customer is stands in another table. `merge` joins two tables by a column that both have: the key.\n",
    "\n",
    "### 7.1 Two small tables\n",
    "\n",
    "Change it and run: add `\"Jacket\"` with the price 129.0 to `prices`. The fourth row appears."
   ],
   "id": "t11-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "sales = pd.DataFrame({\n",
    "    \"product\": [\"Mug\", \"Novel\", \"Mug\", \"Jacket\"],\n",
    "    \"units\": [2, 1, 3, 1],\n",
    "})\n",
    "prices = pd.DataFrame({\n",
    "    \"product\": [\"Mug\", \"Novel\", \"Pillow\"],\n",
    "    \"price\": [8.5, 12.5, 22.0],\n",
    "})\n",
    "print(sales.merge(prices, on=\"product\"))"
   ],
   "id": "t11-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For every row of `sales`, pandas looks up the row of `prices` with the same `product` and puts the two side by side. Mug appears twice in `sales`, so its price is used twice.\n",
    "\n",
    "Look at what is missing: Jacket has no price, and Pillow was never sold. Rows without a partner are left out. This is called an inner join.\n",
    "\n",
    "### 7.2 Keeping all rows of the left table: `how=\"left\"`\n",
    "\n",
    "Change it and run: use `how=\"outer\"`. Pillow appears too."
   ],
   "id": "t11-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(sales.merge(prices, on=\"product\", how=\"left\"))"
   ],
   "id": "t11-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `how=\"left\"` every row of the left table stays. Where no partner exists, the new columns get a missing value: the Jacket has no price.\n",
    "\n",
    "| `how=` | Which rows are kept |\n",
    "| --- | --- |\n",
    "| `\"inner\"` (the default) | only rows with a partner in both tables |\n",
    "| `\"left\"` | all rows of the left table |\n",
    "| `\"right\"` | all rows of the right table |\n",
    "| `\"outer\"` | all rows of both tables |\n",
    "\n",
    "In practice `\"left\"` is the most used: your main table keeps all its rows, and you see what could not be matched.\n",
    "\n",
    "### 7.3 The second file: `customers.csv`"
   ],
   "id": "t11-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "customers = pd.read_csv(\"customers.csv\")\n",
    "print(customers.head())\n",
    "print(customers.shape)"
   ],
   "id": "t11-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Column | Meaning |\n",
    "| --- | --- |\n",
    "| `customer` | the first name, as in `orders.csv` |\n",
    "| `age` | the age in years |\n",
    "| `gender` | `F` or `M` |\n",
    "| `joined` | the year the customer registered |\n",
    "\n",
    "### 7.4 Orders with their customers\n",
    "\n",
    "Change it and run: show the column `joined` too."
   ],
   "id": "t11-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "customers = pd.read_csv(\"customers.csv\")\n",
    "full = df.merge(customers, on=\"customer\", how=\"left\")\n",
    "print(full.shape)\n",
    "print(full[[\"date\", \"customer\", \"product\", \"age\", \"gender\"]].head(4))"
   ],
   "id": "t11-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Still 300 rows, now with 11 columns. Each order has the age, the gender and the year of its customer.\n",
    "\n",
    "### 7.5 Always check what did not match"
   ],
   "id": "t11-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(full[\"age\"].isna().sum())\n",
    "print(full[full[\"age\"].isna()][\"customer\"].unique().tolist())\n",
    "\n",
    "inner = df.merge(customers, on=\"customer\")\n",
    "print(len(inner))"
   ],
   "id": "t11-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Three orders belong to customers who are not in `customers.csv`. A left join shows them as gaps. An inner join would silently lose these three orders.\n",
    "\n",
    "### 7.6 Using the joined table\n",
    "\n",
    "Change it and run: count the orders of customers who are 50 or older."
   ],
   "id": "t11-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "full[\"total\"] = full[\"price\"] * full[\"units\"]\n",
    "print(full.groupby(\"gender\")[\"total\"].agg([\"count\", \"sum\"]).round(2))\n",
    "print(len(full[full[\"age\"] < 30]))"
   ],
   "id": "t11-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After the join, the new columns work like all others: grouping by `gender`, filtering by `age`.\n",
    "\n",
    "### 7.7 Keys with different names\n",
    "\n",
    "When the key has another name in the second table, name both: `orders.merge(people, left_on=\"customer\", right_on=\"name\")`.\n",
    "\n",
    "### 7.8 Stacking tables: `concat`\n",
    "\n",
    "`merge` puts tables side by side. `concat` puts tables with the same columns under each other, for example the files of two months:\n",
    "\n",
    "Change it and run: remove `ignore_index=True` and look at the row labels."
   ],
   "id": "t11-087"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "january = pd.DataFrame({\"product\": [\"Mug\", \"Novel\"], \"units\": [2, 1]})\n",
    "february = pd.DataFrame({\"product\": [\"Jacket\", \"Mug\"], \"units\": [1, 4]})\n",
    "both = pd.concat([january, february], ignore_index=True)\n",
    "print(both)"
   ],
   "id": "t11-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`ignore_index=True` numbers the rows again from 0.\n",
    "\n",
    "| You write | What it does |\n",
    "| --- | --- |\n",
    "| `a.merge(b, on=\"key\")` | joins by a column; keeps rows with a partner in both tables |\n",
    "| `a.merge(b, on=\"key\", how=\"left\")` | keeps all rows of `a` |\n",
    "| `a.merge(b, left_on=\"x\", right_on=\"y\")` | the key has different names |\n",
    "| `pd.concat([a, b], ignore_index=True)` | puts `b` under `a` |\n",
    "\n",
    "## 8. From the file to the answer\n",
    "\n",
    "A real task uses all steps together. The question: which category earns the most money in each city, and how do customers under 30 rate their orders?\n",
    "\n",
    "### 8.1 Step 1: read, look and clean"
   ],
   "id": "t11-089"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.isna().sum().sum())\n",
    "print(df.duplicated().sum())\n",
    "\n",
    "df[\"city\"] = df[\"city\"].fillna(\"Unknown\")\n",
    "df[\"date\"] = pd.to_datetime(df[\"date\"])\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "print(df.isna().sum().sum())\n",
    "print(df.dtypes[\"date\"])"
   ],
   "id": "t11-090"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "44 gaps and no duplicates. The city gets the word \"Unknown\". The ratings stay as they are: a missing rating is information, and summaries skip it. The date becomes a real date, and every order gets its total.\n",
    "\n",
    "### 8.2 Step 2: group\n",
    "\n",
    "Change it and run: put the number of orders into the cells: `values=\"price\", aggfunc=\"count\"`."
   ],
   "id": "t11-091"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"city\"] = df[\"city\"].fillna(\"Unknown\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "\n",
    "money = df.pivot_table(index=\"city\", columns=\"category\", values=\"total\", aggfunc=\"sum\")\n",
    "print(money.round(0))\n",
    "print(money.idxmax(axis=1))"
   ],
   "id": "t11-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`idxmax(axis=1)` gives, for every row, the label of the column with the largest value: the strongest category of every city.\n",
    "\n",
    "### 8.3 Step 3: join and filter\n",
    "\n",
    "Change it and run: use 40 instead of 30 as the limit."
   ],
   "id": "t11-093"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "customers = pd.read_csv(\"customers.csv\")\n",
    "full = df.merge(customers, on=\"customer\", how=\"left\")\n",
    "\n",
    "young = full[full[\"age\"] < 30]\n",
    "older = full[full[\"age\"] >= 30]\n",
    "print(len(young), round(young[\"rating\"].mean(), 2))\n",
    "print(len(older), round(older[\"rating\"].mean(), 2))"
   ],
   "id": "t11-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The order of the work is almost always the same: look, clean, add columns, join, filter, group.\n",
    "\n",
    "## 9. Common mistakes\n",
    "\n",
    "The red text is the real message Python shows. Where there is no message, the program runs but does the wrong thing: the comment shows what it prints.\n",
    "\n",
    "| Mistake | What happens | Fix |\n",
    "| --- | --- | --- |\n",
    "| `and` / `or` between conditions | `ValueError`: the truth value of a Series is ambiguous | `&` and `\\|` |\n",
    "| No parentheses around the conditions | `ValueError` | `(df[\"price\"] > 100) & (df[\"units\"] > 1)` |\n",
    "| One `=` in a condition: `df[\"city\"] = \"Baku\"` | the whole column is overwritten | `==` compares |\n",
    "| `== NaN` to find missing values | nothing is found | `isna()` |\n",
    "| `df[\"city\"].fillna(\"Unknown\")` without storing it | the gaps are still there | `df[\"city\"] = df[\"city\"].fillna(\"Unknown\")` |\n",
    "| `isin(\"Baku\")` with a text | `TypeError` | a list: `isin([\"Baku\"])` |\n",
    "| `pd.to_numeric` on a column with wrong values | `ValueError` | `errors=\"coerce\"` |\n",
    "| Text that is not cleaned before counting | `\"baku\"` and `\"Baku \"` are different groups | `str.strip().str.title()` first |\n",
    "| `df.groupby(\"city\")` without a summary | no result, only a group object | add `.mean()`, `.sum()`, `.size()` |\n",
    "| The mean of a text column in a `groupby` | `TypeError` | choose the column first: `groupby(\"city\")[\"price\"].mean()` |\n",
    "| A wrong key name in `merge` | `KeyError` | check `columns` of both tables |\n",
    "| An inner join that loses rows | fewer rows than before, without a message | `how=\"left\"`, then count the gaps |\n",
    "\n",
    "`and` between two conditions:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df[(df[\"price\"] > 100) and (df[\"units\"] > 1)])\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().\n",
    "```\n",
    "\n",
    "Conditions without parentheses:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df[df[\"price\"] > 100 & df[\"units\"] > 1])\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().\n",
    "```\n",
    "\n",
    "`isin` with a text instead of a list:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df[df[\"city\"].isin(\"Baku\")])\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: only list-like objects are allowed to be passed to isin(), you passed a `str`\n",
    "```\n",
    "\n",
    "`fillna` without storing the result:"
   ],
   "id": "t11-095"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"city\"].fillna(\"Unknown\")\n",
    "print(df[\"city\"].isna().sum())\n",
    "\n",
    "df[\"city\"] = df[\"city\"].fillna(\"Unknown\")\n",
    "print(df[\"city\"].isna().sum())"
   ],
   "id": "t11-096"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A wrong key name in `merge`:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "customers = pd.read_csv(\"customers.csv\")\n",
    "full = df.merge(customers, on=\"name\")\n",
    "```\n",
    "\n",
    "```\n",
    "KeyError: 'name'\n",
    "```\n",
    "\n",
    "## 10. Solved problems (easy to medium-hard)\n",
    "\n",
    "Every example was run, and the outputs are real.\n",
    "\n",
    "### 10.1 Level 1: Easy\n",
    "\n",
    "Problem 1. The orders of one city\n",
    "\n",
    "Change it and run: do the same for Lankaran."
   ],
   "id": "t11-097"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "quba = df[df[\"city\"] == \"Quba\"]\n",
    "print(len(quba))\n",
    "print(quba[[\"date\", \"customer\", \"product\"]].head(3))"
   ],
   "id": "t11-098"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 2. How many gaps?"
   ],
   "id": "t11-099"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "gaps = df.isna().sum()\n",
    "print(gaps[gaps > 0])"
   ],
   "id": "t11-100"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `isna().sum()` is a Series, and a condition keeps only the columns that have gaps.\n",
    "\n",
    "Problem 3. Orders with five units\n",
    "\n",
    "Change it and run: show the orders with 4 units."
   ],
   "id": "t11-101"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.loc[df[\"units\"] == 5, [\"customer\", \"product\", \"price\"]])"
   ],
   "id": "t11-102"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 4. Fill the missing cities\n",
    "\n",
    "Change it and run: fill with `\"?\"` and print all counts."
   ],
   "id": "t11-103"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"city\"] = df[\"city\"].fillna(\"Unknown\")\n",
    "print(df[\"city\"].value_counts().tail(3))"
   ],
   "id": "t11-104"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 5. The average rating of every category\n",
    "\n",
    "Change it and run: print the median rating instead of the mean."
   ],
   "id": "t11-105"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.groupby(\"category\")[\"rating\"].mean().round(2))"
   ],
   "id": "t11-106"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 10.2 Level 2: Medium\n",
    "\n",
    "Problem 6. Expensive orders outside Baku\n",
    "\n",
    "Change it and run: change the limit to 200."
   ],
   "id": "t11-107"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "chosen = df[(df[\"price\"] > 100) & (df[\"city\"] != \"Baku\")]\n",
    "print(len(chosen))\n",
    "print(chosen[[\"customer\", \"city\", \"product\", \"price\"]].head(4))"
   ],
   "id": "t11-108"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: two conditions with `&`, each in parentheses. `!=` means \"not equal\". (The rows without a city are counted too: a missing city is not equal to \"Baku\".)\n",
    "\n",
    "Problem 7. Bad ratings\n",
    "\n",
    "Change it and run: count the ratings of exactly 5 instead."
   ],
   "id": "t11-109"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "bad = df[df[\"rating\"] <= 2]\n",
    "print(len(bad))\n",
    "print(bad[\"product\"].value_counts().head(2))"
   ],
   "id": "t11-110"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: filter first, then count: these products get the low ratings most often.\n",
    "\n",
    "Problem 8. A cleaned price column\n",
    "\n",
    "Change it and run: add a fifth product with the price `\"45,90\"`."
   ],
   "id": "t11-111"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "shop = pd.DataFrame({\n",
    "    \"product\": [\"Mug\", \"Novel\", \"Jacket\", \"Pillow\"],\n",
    "    \"price\": [\"8.50\", \"12,50\", \"129\", \"unknown\"],\n",
    "})\n",
    "shop[\"price\"] = shop[\"price\"].str.replace(\",\", \".\")\n",
    "shop[\"price\"] = pd.to_numeric(shop[\"price\"], errors=\"coerce\")\n",
    "print(shop)\n",
    "print(shop[\"price\"].mean())"
   ],
   "id": "t11-112"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the comma is replaced by a point first. Then `to_numeric` converts what it can, and \"unknown\" becomes a missing value, which the mean skips.\n",
    "\n",
    "Problem 9. The money of every city\n",
    "\n",
    "Change it and run: leave out the first line. The city `Unknown` disappears."
   ],
   "id": "t11-113"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"city\"] = df[\"city\"].fillna(\"Unknown\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "money = df.groupby(\"city\")[\"total\"].sum().sort_values(ascending=False)\n",
    "print(money.round(2))"
   ],
   "id": "t11-114"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 10. The best customers\n",
    "\n",
    "Change it and run: sort by `count` instead of `sum`."
   ],
   "id": "t11-115"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "best = df.groupby(\"customer\")[\"total\"].agg([\"count\", \"sum\"])\n",
    "print(best.sort_values(\"sum\", ascending=False).head(5).round(2))"
   ],
   "id": "t11-116"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `agg` gives the number of orders and the money of every customer. Sorting by `sum` puts the most valuable customers first.\n",
    "\n",
    "### 10.3 Level 3: Medium-Hard\n",
    "\n",
    "Problem 11. Orders and money by weekday"
   ],
   "id": "t11-117"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "df[\"weekday\"] = pd.to_datetime(df[\"date\"]).dt.day_name()\n",
    "days = df.groupby(\"weekday\")[\"total\"].agg([\"count\", \"mean\"])\n",
    "print(days.round(2))"
   ],
   "id": "t11-118"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 12. A cleaned table of visitors\n",
    "\n",
    "Change it and run: change `\"twenty-two\"` to `\"22\"`. The row stays, and the second Leyla is removed as a duplicate."
   ],
   "id": "t11-119"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "raw = pd.DataFrame({\n",
    "    \"name\": [\" aylin\", \"MURAD \", \"Leyla\", \"leyla\", \"Kamran\"],\n",
    "    \"city\": [\"baku\", \"Baku \", \"GANJA\", \"Ganja\", \"baku\"],\n",
    "    \"age\": [\"20\", \"25\", \"twenty-two\", \"22\", \"30\"],\n",
    "})\n",
    "raw[\"name\"] = raw[\"name\"].str.strip().str.title()\n",
    "raw[\"city\"] = raw[\"city\"].str.strip().str.title()\n",
    "raw[\"age\"] = pd.to_numeric(raw[\"age\"], errors=\"coerce\")\n",
    "clean = raw.dropna().drop_duplicates(subset=[\"name\"])\n",
    "print(clean)\n",
    "print(clean.groupby(\"city\")[\"age\"].mean())"
   ],
   "id": "t11-120"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: text first, then the numbers, then the row with a gap is removed, then the duplicates. After the cleaning, a `groupby` gives correct groups.\n",
    "\n",
    "Problem 13. Age groups\n",
    "\n",
    "Change it and run: use 40 as the limit instead of 30."
   ],
   "id": "t11-121"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "customers = pd.read_csv(\"customers.csv\")\n",
    "full = df.merge(customers, on=\"customer\", how=\"left\")\n",
    "full[\"total\"] = full[\"price\"] * full[\"units\"]\n",
    "\n",
    "full[\"group\"] = \"30 and older\"\n",
    "full.loc[full[\"age\"] < 30, \"group\"] = \"under 30\"\n",
    "full.loc[full[\"age\"].isna(), \"group\"] = \"unknown\"\n",
    "print(full.groupby(\"group\")[\"total\"].agg([\"count\", \"mean\"]).round(2))"
   ],
   "id": "t11-122"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a new column starts with one value, and `loc` with a condition changes it for the chosen rows. The customers without an age get their own group, so no order is lost.\n",
    "\n",
    "Problem 14. Customers who never ordered"
   ],
   "id": "t11-123"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "customers = pd.read_csv(\"customers.csv\")\n",
    "buyers = df[\"customer\"].unique()\n",
    "quiet = customers[~customers[\"customer\"].isin(buyers)]\n",
    "print(quiet)"
   ],
   "id": "t11-124"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `isin` marks the customers who appear in the orders, and `~` turns the mask around.\n",
    "\n",
    "Problem 15. The best month of every category\n",
    "\n",
    "Change it and run: group by `city` instead of `category`: the best month of every city."
   ],
   "id": "t11-125"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "df[\"month\"] = pd.to_datetime(df[\"date\"]).dt.month\n",
    "table = df.pivot_table(index=\"category\", columns=\"month\", values=\"total\", aggfunc=\"sum\")\n",
    "print(table.idxmax(axis=1))\n",
    "print(table.max(axis=1).round(2))"
   ],
   "id": "t11-126"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the pivot table has one row for every category and one column for every month. `idxmax(axis=1)` finds the month with the most money in each row, and `max(axis=1)` the money itself.\n",
    "\n",
    "## 13. Quick summary\n",
    "\n",
    "| Concept | What it does | Example |\n",
    "| --- | --- | --- |\n",
    "| Mask | `True`/`False` for every row | `df[\"price\"] > 100` |\n",
    "| Filter | the rows where the mask is `True` | `df[df[\"price\"] > 100]` |\n",
    "| `&`, `\\|`, `~` | and, or, not | `(a) & (b)` |\n",
    "| `isin` / `between` | one of a list / from a to b | `df[\"city\"].isin([\"Shaki\", \"Quba\"])` |\n",
    "| `str.contains` | the text has this piece | `df[\"product\"].str.contains(\"book\")` |\n",
    "| `isna` / `notna` | missing / not missing | `df.isna().sum()` |\n",
    "| `dropna` / `fillna` | removes / fills gaps | `df[\"city\"].fillna(\"Unknown\")` |\n",
    "| `duplicated` / `drop_duplicates` | finds / removes repeated rows | `df.drop_duplicates()` |\n",
    "| `pd.to_numeric` | text to numbers | `pd.to_numeric(col, errors=\"coerce\")` |\n",
    "| `pd.to_datetime` / `.dt` | text to dates / parts of a date | `df[\"date\"].dt.month` |\n",
    "| `select_dtypes` | columns of one kind | `df.select_dtypes(include=\"number\")` |\n",
    "| `.str` methods | cleans text | `col.str.strip().str.title()` |\n",
    "| `groupby` | a summary for every group | `df.groupby(\"city\")[\"price\"].mean()` |\n",
    "| `agg` | several summaries | `.agg([\"count\", \"mean\"])` |\n",
    "| `pivot_table` | groups in rows and columns | `df.pivot_table(index=, columns=, values=)` |\n",
    "| `merge` | joins two tables by a key | `df.merge(customers, on=\"customer\", how=\"left\")` |\n",
    "| `concat` | stacks tables | `pd.concat([a, b], ignore_index=True)` |\n",
    "\n",
    "Golden rules\n",
    "\n",
    "1. Look before you clean: `info()`, `isna().sum()`, `duplicated().sum()`, `value_counts()`.\n",
    "2. A condition gives a mask, and the mask chooses rows. Use `&`, `|`, `~` with parentheses.\n",
    "3. Missing values are found with `isna()`, never with `==`.\n",
    "4. Cleaning methods give a new column. Store it: `df[\"city\"] = df[\"city\"].fillna(\"Unknown\")`.\n",
    "5. Clean text and types before you count or group.\n",
    "6. Read a `groupby` from left to right: the groups, the column, the summary.\n",
    "7. Join with `how=\"left\"`, then count the gaps to see what did not match.\n",
    "\n",
    "Next: the practice notebook (topic-11-practice.ipynb), then Topic 12: Data visualization: Matplotlib and Seaborn basics."
   ],
   "id": "t11-127"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
