{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 10: Pandas fundamentals: Series and DataFrames, reading data\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 5, Thursday.\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-10-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 file orders.csv. Put the file into the same folder as the notebook. On the Asiman Data School website the file is already there.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. pandas and the Series\n",
    "2. DataFrames\n",
    "3. Reading data\n",
    "4. A first look at a table\n",
    "5. Choosing columns\n",
    "6. Choosing rows by position: iloc\n",
    "7. Choosing rows by label: loc\n",
    "8. Sorting\n",
    "9. New columns and changing columns\n",
    "10. Common mistakes\n",
    "11. Solved problems (easy to medium-hard)\n",
    "12. Practice problems (try them yourself) (in topic-10-practice.ipynb)\n",
    "13. Check yourself (on the website)\n",
    "14. Quick summary"
   ],
   "id": "t10-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: pandas, Series and DataFrames\n",
    "\n",
    "What matters most in this lesson. Five things matter most today: reading a file with `pd.read_csv`; looking at a new table with `head`, `shape`, `info` and `describe`; choosing columns with `df[\"price\"]` and `df[[\"product\", \"price\"]]`; choosing rows with `iloc` (positions) and `loc` (labels); and making a new column from a calculation.\n",
    "\n",
    "The Series comes first because every column of a table is one. `set_index`, `astype`, `parse_dates` and the options of `read_csv` are tools you will meet again, so a first look is enough today. There are 15 solved problems. Start with Level 1 and come back for the rest.\n",
    "\n",
    "A beginner-friendly guide to pandas, the library for working with tables of data in Python. It starts with the two building blocks, the Series (one column) and the DataFrame (a whole table). Then it reads a real data file and shows how to look at a table, how to choose columns and rows with `[]`, `iloc` and `loc`, how to sort a table and how to add new columns. 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 lists, dictionaries and NumPy arrays: indexes, slices and calculations on whole arrays.\n",
    "\n",
    "The data file. All examples with real data use one file, `orders.csv`: 300 orders of a small online shop in 2025. Put the file into the same folder as your notebook. The next lessons use the same file.\n",
    "\n",
    "This lesson and the next one. This lesson is about reading a table, looking at it and choosing parts of it. The next lesson continues with missing values, choosing rows by a condition, joining two tables and grouping. Those topics are left out here on purpose.\n",
    "\n",
    "## 1. pandas and the Series\n",
    "\n",
    "### 1.1 What is pandas?\n",
    "\n",
    "pandas is a package for working with tables of data: rows and columns with names, like a spreadsheet. It is built on NumPy, and almost every data project in Python starts with it: reading a file, looking at the data, preparing it for charts and models.\n",
    "\n",
    "With Anaconda, pandas is already installed. Everybody imports it with the short name `pd`:"
   ],
   "id": "t10-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "print(pd.__version__)"
   ],
   "id": "t10-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2 Two building blocks\n",
    "\n",
    "|  | What it is | Think of it as |\n",
    "| --- | --- | --- |\n",
    "| Series | one column of values, and every value has a label | one column of a spreadsheet |\n",
    "| DataFrame | a table: several columns side by side | the whole spreadsheet |\n",
    "\n",
    "A DataFrame is made of Series: every column of a DataFrame is a Series.\n",
    "\n",
    "### 1.3 Why not just a NumPy array?\n",
    "\n",
    "|  | NumPy array | pandas DataFrame |\n",
    "| --- | --- | --- |\n",
    "| Types | one type for all items | every column has its own type |\n",
    "| Rows and columns | reached by position | have names (labels) |\n",
    "| Made for | numbers and calculation | real data: names, dates, prices, gaps |\n",
    "| Reading files | not its job | one line for a CSV or an Excel file |\n",
    "\n",
    "What you learned about arrays still works: calculations on whole columns, `sum`, `mean`, `max`.\n",
    "\n",
    "### 1.4 A Series from a list\n",
    "\n",
    "Change it and run: add a fifth grade to the list. Which label does it get?"
   ],
   "id": "t10-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = pd.Series([85, 92, 78, 60])\n",
    "print(grades)"
   ],
   "id": "t10-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The left side is the index: the labels of the values. If you give no labels, pandas numbers them from 0. The right side holds the values, and the last line shows their type.\n",
    "\n",
    "### 1.5 Your own labels\n",
    "\n",
    "Change it and run: change the label `Kamran` to your own name."
   ],
   "id": "t10-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = pd.Series([85, 92, 78, 60], index=[\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"])\n",
    "print(grades)"
   ],
   "id": "t10-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now every value has a name. This is the big difference from a NumPy array.\n",
    "\n",
    "### 1.6 A Series from a dictionary\n",
    "\n",
    "The keys become the labels:\n",
    "\n",
    "Change it and run: add `\"eggs\": 3.2` to the dictionary."
   ],
   "id": "t10-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = pd.Series({\"apple\": 1.5, \"bread\": 0.8, \"milk\": 2.0})\n",
    "print(prices)"
   ],
   "id": "t10-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.7 The parts of a Series"
   ],
   "id": "t10-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(grades.values)\n",
    "print(grades.index)\n",
    "print(grades.dtype)\n",
    "print(grades.size)"
   ],
   "id": "t10-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`values` is a NumPy array. `index` holds the labels. `dtype` and `size` mean the same as for an array.\n",
    "\n",
    "### 1.8 Reaching a value: by label or by position\n",
    "\n",
    "Change it and run: print Leyla's grade in two ways: with her label and with her position."
   ],
   "id": "t10-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(grades[\"Murad\"])\n",
    "print(grades.loc[\"Murad\"])\n",
    "print(grades.iloc[1])\n",
    "print(grades.iloc[-1])"
   ],
   "id": "t10-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`loc` uses the label. `iloc` uses the position, counted from 0 as in a list (the `i` stands for integer). Square brackets alone work with labels.\n",
    "\n",
    "### 1.9 Several values, and slices\n",
    "\n",
    "Change it and run: print the first three grades with `iloc`, then the same three with `loc`."
   ],
   "id": "t10-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(grades[[\"Aylin\", \"Leyla\"]])\n",
    "print(grades.iloc[1:3])\n",
    "print(grades.loc[\"Murad\":\"Kamran\"])"
   ],
   "id": "t10-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A slice by position stops before its end, as always. A slice by label includes its end: `\"Murad\":\"Kamran\"` takes Kamran too.\n",
    "\n",
    "### 1.10 A label that does not exist\n",
    "\n",
    "```python\n",
    "print(grades[\"Nigar\"])\n",
    "```\n",
    "\n",
    "```\n",
    "KeyError: 'Nigar'\n",
    "```\n",
    "\n",
    "`in` checks whether a label exists: `\"Nigar\" in grades` gives `False`.\n",
    "\n",
    "### 1.11 Changing and adding values\n",
    "\n",
    "Change it and run: give Aylin the grade 100."
   ],
   "id": "t10-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades[\"Murad\"] = 95\n",
    "grades[\"Nigar\"] = 70\n",
    "print(grades)"
   ],
   "id": "t10-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A label that exists is changed. A new label is added at the end, as in a dictionary.\n",
    "\n",
    "### 1.12 Calculations on a whole Series\n",
    "\n",
    "A Series calculates like a NumPy array: on every value at once. The labels stay.\n",
    "\n",
    "Change it and run: print `grades * 2`."
   ],
   "id": "t10-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "grades = pd.Series([85, 92, 78, 60], index=[\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"])\n",
    "print(grades + 5)\n",
    "print(grades / 100)"
   ],
   "id": "t10-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.13 Summaries\n",
    "\n",
    "Change it and run: change Kamran's grade from 60 to 99 in the list. Which results change?"
   ],
   "id": "t10-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(grades.sum())\n",
    "print(grades.mean())\n",
    "print(grades.min(), grades.max())\n",
    "print(grades.idxmax())\n",
    "print(grades.idxmin())"
   ],
   "id": "t10-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`idxmax` and `idxmin` give the label of the largest and the smallest value. (NumPy's `argmax` gave the position.)\n",
    "\n",
    "### 1.14 Sorting a Series\n",
    "\n",
    "Change it and run: print only the two best grades: `grades.sort_values(ascending=False).iloc[:2]`."
   ],
   "id": "t10-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(grades.sort_values())\n",
    "print(grades.sort_values(ascending=False))\n",
    "print(grades.sort_index())"
   ],
   "id": "t10-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`sort_values` sorts by the values, `sort_index` sorts by the labels. Each value keeps its label. All three give a new Series: `grades` itself is not changed.\n",
    "\n",
    "### 1.15 From a Series to a list or an array"
   ],
   "id": "t10-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(grades.tolist())\n",
    "print(grades.to_numpy())"
   ],
   "id": "t10-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| You write | You get |\n",
    "| --- | --- |\n",
    "| `pd.Series([85, 92], index=[\"Aylin\", \"Murad\"])` | a Series with your own labels |\n",
    "| `s[\"Murad\"]`, `s.loc[\"Murad\"]` | the value with this label |\n",
    "| `s.iloc[0]`, `s.iloc[-1]` | the value at this position |\n",
    "| `s[[\"Aylin\", \"Leyla\"]]` | several values, as a Series |\n",
    "| `s.iloc[1:3]` | a slice by position: the end is not included |\n",
    "| `s.loc[\"Murad\":\"Kamran\"]` | a slice by label: the end is included |\n",
    "| `s.sum()`, `s.mean()`, `s.min()`, `s.max()` | summaries |\n",
    "| `s.idxmax()`, `s.idxmin()` | the label of the largest / smallest value |\n",
    "| `s.sort_values()`, `s.sort_index()` | a sorted copy |\n",
    "| `s.tolist()`, `s.to_numpy()` | a list / a NumPy array |\n",
    "\n",
    "## 2. DataFrames\n",
    "\n",
    "### 2.1 A DataFrame from a dictionary\n",
    "\n",
    "Each key is the name of a column, and each list holds the values of that column:\n",
    "\n",
    "Change it and run: add a fourth column, `\"city\"`, with four cities."
   ],
   "id": "t10-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.DataFrame({\n",
    "    \"name\": [\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"],\n",
    "    \"age\": [20, 25, 22, 30],\n",
    "    \"grade\": [85.5, 92.0, 78.0, 60.5],\n",
    "})\n",
    "print(df)"
   ],
   "id": "t10-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The name `df` is short for DataFrame. Almost everybody uses it.\n",
    "\n",
    "```\n",
    "                 columns:    name    age   grade\n",
    "   index (row labels)\n",
    "          0                 Aylin     20    85.5\n",
    "          1                 Murad     25    92.0\n",
    "          2                 Leyla     22    78.0\n",
    "          3                Kamran     30    60.5\n",
    "```\n",
    "\n",
    "A DataFrame has three parts: the columns (their names are on top), the index (the row labels on the left) and the values.\n",
    "\n",
    "### 2.2 The lists must have the same length\n",
    "\n",
    "```python\n",
    "df = pd.DataFrame({\n",
    "    \"name\": [\"Aylin\", \"Murad\", \"Leyla\"],\n",
    "    \"age\": [20, 25],\n",
    "})\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: All arrays must be of the same length\n",
    "```\n",
    "\n",
    "### 2.3 The properties of a DataFrame\n",
    "\n",
    "Change it and run: add a fifth student to the three lists. What is the shape now?"
   ],
   "id": "t10-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.shape)\n",
    "print(len(df))\n",
    "print(df.columns)\n",
    "print(df.index)\n",
    "print(df.dtypes)"
   ],
   "id": "t10-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`shape` is `(rows, columns)`, as in NumPy, and `len` is the number of rows. `dtypes` lists the type of every column. (Its last line, `dtype: object`, belongs to that list itself, not to the table.)\n",
    "\n",
    "| dtype | Meaning |\n",
    "| --- | --- |\n",
    "| `int64` | whole numbers |\n",
    "| `float64` | decimals |\n",
    "| `str` | text (older pandas versions show `object` here) |\n",
    "| `bool` | `True` and `False` |\n",
    "| `datetime64` | dates (Part 3) |\n",
    "\n",
    "### 2.4 Every column is a Series\n",
    "\n",
    "Change it and run: print the `grade` column and its largest value."
   ],
   "id": "t10-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ages = df[\"age\"]\n",
    "print(ages)\n",
    "print(type(ages))\n",
    "print(ages.mean())"
   ],
   "id": "t10-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The column has the same index as the table, and its name is the column name. Everything about a Series from Part 1 works on it.\n",
    "\n",
    "### 2.5 A DataFrame from a list of rows\n",
    "\n",
    "When the data comes row by row, use a list of dictionaries. Each dictionary is one row:\n",
    "\n",
    "Change it and run: add a fourth row, `{\"name\": \"Kamran\", \"age\": 30}`."
   ],
   "id": "t10-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rows = [\n",
    "    {\"name\": \"Aylin\", \"age\": 20},\n",
    "    {\"name\": \"Murad\", \"age\": 25},\n",
    "    {\"name\": \"Leyla\", \"age\": 22},\n",
    "]\n",
    "df = pd.DataFrame(rows)\n",
    "print(df)"
   ],
   "id": "t10-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.6 Your own row labels\n",
    "\n",
    "As with a Series, `index=` gives the rows your own labels:"
   ],
   "id": "t10-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "students = pd.DataFrame(\n",
    "    {\"age\": [20, 25, 22, 30], \"grade\": [85.5, 92.0, 78.0, 60.5]},\n",
    "    index=[\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"],\n",
    ")\n",
    "print(students)"
   ],
   "id": "t10-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now the names are not a column. They are the labels of the rows. We use this table again in Part 7.\n",
    "\n",
    "## 3. Reading data\n",
    "\n",
    "Real data is not typed by hand. It comes from files.\n",
    "\n",
    "### 3.1 What is a CSV file?\n",
    "\n",
    "CSV means \"comma-separated values\". It is a plain text file: one line for every row, the values separated by commas, and the column names in the first line. These are the first lines of `orders.csv`:\n",
    "\n",
    "```\n",
    "date,customer,city,category,product,price,units,rating\n",
    "2025-01-01,Nigar,Baku,Home,Mug,8.50,2,5\n",
    "2025-01-03,Ziya,Lankaran,Clothing,Jacket,129.00,1,3\n",
    "2025-01-11,Anar,Ganja,Books,Cookbook,24.90,4,5\n",
    "```\n",
    "\n",
    "### 3.2 `read_csv`\n",
    "\n",
    "One line reads the whole file into a DataFrame:\n",
    "\n",
    "Change it and run: print `len(df)`: the number of rows."
   ],
   "id": "t10-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df)"
   ],
   "id": "t10-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A long table is printed in a short form: the first five and the last five rows, and its size below.\n",
    "\n",
    "The file must be in the same folder as your notebook. If it is somewhere else, write the path: `pd.read_csv(\"data/orders.csv\")`.\n",
    "\n",
    "### 3.3 The columns of `orders.csv`\n",
    "\n",
    "| Column | Meaning | Example |\n",
    "| --- | --- | --- |\n",
    "| `date` | the day of the order | `2025-01-03` |\n",
    "| `customer` | the first name of the customer | `Ziya` |\n",
    "| `city` | the city of the customer | `Lankaran` |\n",
    "| `category` | the product group: Tech, Clothing, Books, Home or Sports | `Clothing` |\n",
    "| `product` | what was bought | `Jacket` |\n",
    "| `price` | the price of one unit, in AZN | `129.00` |\n",
    "| `units` | how many units were bought | `1` |\n",
    "| `rating` | the customer's rating from 1 to 5 (some customers gave none) | `3` |\n",
    "\n",
    "### 3.4 Useful options of `read_csv`\n",
    "\n",
    "| Option | What it does | Example |\n",
    "| --- | --- | --- |\n",
    "| `usecols` | reads only some columns | `usecols=[\"date\", \"price\"]` |\n",
    "| `nrows` | reads only the first rows | `nrows=100` |\n",
    "| `sep` | the separator, if it is not a comma | `sep=\";\"` |\n",
    "| `index_col` | uses a column as the row labels | `index_col=\"date\"` |\n",
    "| `parse_dates` | reads a column as real dates | `parse_dates=[\"date\"]` |\n",
    "\n",
    "Change it and run: read the columns `date` and `city` and the first 6 rows."
   ],
   "id": "t10-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "small = pd.read_csv(\"orders.csv\", usecols=[\"product\", \"price\", \"units\"], nrows=4)\n",
    "print(small)"
   ],
   "id": "t10-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.5 Dates\n",
    "\n",
    "`read_csv` reads the `date` column as text. With `parse_dates` the column holds real dates. They can be compared and sorted, and later used for charts over time:\n",
    "\n",
    "Change it and run: remove the `parse_dates` option and run it again. The type is `str`: the dates are only text."
   ],
   "id": "t10-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\", parse_dates=[\"date\"])\n",
    "print(df[\"date\"].dtype)\n",
    "print(df[\"date\"].min())\n",
    "print(df[\"date\"].max())"
   ],
   "id": "t10-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first and the last order of the year. (The letters in the brackets of `datetime64[...]` can differ between pandas versions.)\n",
    "\n",
    "### 3.6 Excel files\n",
    "\n",
    "An Excel file is read in the same way, with `read_excel`:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_excel(\"orders.xlsx\")\n",
    "```\n",
    "\n",
    "### 3.7 Saving a table: `to_csv`\n",
    "\n",
    "Change it and run: save the first 5 rows instead."
   ],
   "id": "t10-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "first = df.head(3)\n",
    "first.to_csv(\"first_orders.csv\", index=False)\n",
    "\n",
    "with open(\"first_orders.csv\") as file:\n",
    "    print(file.read())"
   ],
   "id": "t10-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`to_csv` writes a table into a new file. `index=False` leaves out the row labels 0, 1, 2. Without it the file gets an extra first column.\n",
    "\n",
    "## 4. A first look at a table\n",
    "\n",
    "Before you work with a table, look at it. These are the first lines of almost every data project.\n",
    "\n",
    "### 4.1 `head` and `tail`\n",
    "\n",
    "Change it and run: print the first 2 rows and the last 6."
   ],
   "id": "t10-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.head())\n",
    "print(df.tail(3))"
   ],
   "id": "t10-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`head()` gives the first 5 rows, `tail()` the last 5. A number in the parentheses changes how many.\n",
    "\n",
    "### 4.2 `shape`, the column names and the types"
   ],
   "id": "t10-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.shape)\n",
    "print(df.columns.tolist())\n",
    "print(df.dtypes)"
   ],
   "id": "t10-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "300 rows and 8 columns. `columns.tolist()` gives the names as a normal list. Five columns are text, `price` and `rating` are decimals and `units` is a whole number.\n",
    "\n",
    "### 4.3 `info`: everything in one summary"
   ],
   "id": "t10-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.info()"
   ],
   "id": "t10-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For every column you see its name, how many values are not missing, and its type. `city` has only 292 values and `rating` only 264: the others are missing. `info` prints by itself, so it needs no `print`. The last line is the memory the table uses, and this number can be different on your computer.\n",
    "\n",
    "### 4.4 Missing values look like `NaN`\n",
    "\n",
    "Change it and run: print `df.head(16)`. A second missing rating appears in row 14."
   ],
   "id": "t10-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.head(10))"
   ],
   "id": "t10-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Look at row 9: the customer gave no rating. pandas shows a missing value as `NaN` (\"not a number\"). Because of these gaps the `rating` column is stored as decimals: 5.0, not 5. What to do with missing values is the subject of the next lesson.\n",
    "\n",
    "### 4.5 `describe`: statistics of the number columns\n",
    "\n",
    "Change it and run: print `df.describe().round(1)`. The numbers are easier to read."
   ],
   "id": "t10-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.describe())"
   ],
   "id": "t10-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Row | Meaning |\n",
    "| --- | --- |\n",
    "| `count` | how many values are not missing |\n",
    "| `mean` | the average |\n",
    "| `std` | the standard deviation: how spread out the values are (you will meet it in the statistics lessons) |\n",
    "| `min`, `max` | the smallest and the largest value |\n",
    "| `25%`, `50%`, `75%` | a quarter, a half and three quarters of the values are below this number |\n",
    "\n",
    "The `50%` row is the median. Read the `price` column: half of the prices are below 35.96, but the mean is 50.64, because a few expensive products pull it up.\n",
    "\n",
    "| You write | You see |\n",
    "| --- | --- |\n",
    "| `df.head()`, `df.tail()` | the first / last 5 rows |\n",
    "| `df.shape` | `(rows, columns)` |\n",
    "| `df.columns.tolist()` | the column names as a list |\n",
    "| `df.dtypes` | the type of every column |\n",
    "| `df.info()` | names, missing values and types in one summary |\n",
    "| `df.describe()` | statistics of the number columns |\n",
    "\n",
    "## 5. Choosing columns\n",
    "\n",
    "### 5.1 One column\n",
    "\n",
    "Change it and run: print the first five customers."
   ],
   "id": "t10-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "products = df[\"product\"]\n",
    "print(products.head())\n",
    "print(type(products))"
   ],
   "id": "t10-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The column name in square brackets gives that column as a Series.\n",
    "\n",
    "### 5.2 Several columns\n",
    "\n",
    "Change it and run: change the order of the three names in the list."
   ],
   "id": "t10-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[[\"product\", \"price\", \"units\"]].head())"
   ],
   "id": "t10-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice the double brackets: the inner pair is a list of column names. The result is a DataFrame, with the columns in the order you asked for.\n",
    "\n",
    "### 5.3 One pair of brackets or two?"
   ],
   "id": "t10-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"price\"].shape)\n",
    "print(df[[\"price\"]].shape)"
   ],
   "id": "t10-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`df[\"price\"]` is a Series: one dimension. `df[[\"price\"]]` is a DataFrame with one column: two dimensions.\n",
    "\n",
    "### 5.4 The short way with a dot\n",
    "\n",
    "`df.price` means the same as `df[\"price\"]`:"
   ],
   "id": "t10-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.price.head(3))"
   ],
   "id": "t10-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It works only for simple names without spaces, and it cannot create a new column. This guide uses the brackets everywhere.\n",
    "\n",
    "### 5.5 Summaries of a column\n",
    "\n",
    "Change it and run: print the mean and the largest number of `units`."
   ],
   "id": "t10-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(round(df[\"price\"].mean(), 2))\n",
    "print(df[\"price\"].median())\n",
    "print(df[\"price\"].min(), df[\"price\"].max())\n",
    "print(df[\"units\"].sum())"
   ],
   "id": "t10-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The average price, the median price, the cheapest and the most expensive price, and the number of units sold in the whole year.\n",
    "\n",
    "### 5.6 Missing values are skipped\n",
    "\n",
    "Change it and run: do the same for the column `city`: `len` and `count`."
   ],
   "id": "t10-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(len(df[\"rating\"]))\n",
    "print(df[\"rating\"].count())\n",
    "print(round(df[\"rating\"].mean(), 2))"
   ],
   "id": "t10-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The column has 300 places, but `count` counts only the 264 ratings that exist. The mean is calculated from those 264.\n",
    "\n",
    "### 5.7 Summaries of several columns"
   ],
   "id": "t10-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[[\"price\", \"units\", \"rating\"]].mean())\n",
    "print(df[[\"price\", \"units\"]].max())"
   ],
   "id": "t10-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A summary of a table gives one result for every column, as a Series.\n",
    "\n",
    "### 5.8 Which values are there? `unique` and `nunique`\n",
    "\n",
    "Change it and run: print the different cities, and how many there are."
   ],
   "id": "t10-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"category\"].unique().tolist())\n",
    "print(df[\"category\"].nunique())\n",
    "print(df[\"customer\"].nunique())\n",
    "print(df[\"product\"].nunique())"
   ],
   "id": "t10-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`unique` gives the different values, and `tolist()` turns them into a normal list. `nunique` counts them: 5 categories, 40 customers, 20 products.\n",
    "\n",
    "### 5.9 How often? `value_counts`\n",
    "\n",
    "Change it and run: count the products instead of the cities."
   ],
   "id": "t10-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"city\"].value_counts())"
   ],
   "id": "t10-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`value_counts` counts how often every value appears, the most frequent first. It is one of the most used methods in pandas. The counts add up to 292, because 8 orders have no city.\n",
    "\n",
    "The result is a Series, and the values of the column are its labels:\n",
    "\n",
    "Change it and run: print how many orders are in the category `\"Tech\"`."
   ],
   "id": "t10-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "counts = df[\"category\"].value_counts()\n",
    "print(counts[\"Books\"])\n",
    "print(counts.idxmax())\n",
    "print(df[\"customer\"].value_counts().head(3))"
   ],
   "id": "t10-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.10 Shares instead of counts\n",
    "\n",
    "Change it and run: multiply the result by 100 to get percent."
   ],
   "id": "t10-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df[\"category\"].value_counts(normalize=True).round(2))"
   ],
   "id": "t10-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With `normalize=True` the result is the share of every value: 0.25 means 25% of the orders.\n",
    "\n",
    "| You write | You get |\n",
    "| --- | --- |\n",
    "| `df[\"price\"]` | one column, as a Series |\n",
    "| `df[[\"product\", \"price\"]]` | several columns, as a DataFrame |\n",
    "| `df[\"price\"].mean()`, `.median()`, `.min()`, `.max()`, `.sum()` | a summary of the column |\n",
    "| `df[\"rating\"].count()` | how many values are not missing |\n",
    "| `df[\"category\"].unique().tolist()` | the different values |\n",
    "| `df[\"category\"].nunique()` | how many different values |\n",
    "| `df[\"city\"].value_counts()` | how often every value appears |\n",
    "\n",
    "## 6. Choosing rows by position: `iloc`\n",
    "\n",
    "`iloc` works like indexing a NumPy table: `df.iloc[rows, columns]`. Positions start at 0, and a slice stops before its end.\n",
    "\n",
    "### 6.1 One row\n",
    "\n",
    "Change it and run: print the last row: `df.iloc[-1]`."
   ],
   "id": "t10-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "row = df.iloc[0]\n",
    "print(row)\n",
    "print(row[\"product\"], row[\"price\"])"
   ],
   "id": "t10-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One row comes back as a Series. Its labels are the column names, so `row[\"product\"]` reads one value of the row. `Name: 0` is the label of the row, and the type is `object` because the row mixes text and numbers.\n",
    "\n",
    "### 6.2 Several rows\n",
    "\n",
    "Change it and run: print the rows at the positions 10, 11 and 12."
   ],
   "id": "t10-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.iloc[2:5])\n",
    "print(df.iloc[[0, 100, 200]])\n",
    "print(df.iloc[-2:])"
   ],
   "id": "t10-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A slice, a list of positions, and negative positions all work as with arrays. The results are DataFrames.\n",
    "\n",
    "### 6.3 Rows and columns\n",
    "\n",
    "Change it and run: print the last three columns of the first two rows."
   ],
   "id": "t10-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.iloc[0:3, 0:2])\n",
    "print(df.iloc[:3, [4, 5]])\n",
    "print(df.iloc[0, 4])"
   ],
   "id": "t10-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Rows first, then columns. `df.iloc[0, 4]` is one value: row 0, column 4 (the product).\n",
    "\n",
    "### 6.4 A position that does not exist\n",
    "\n",
    "```python\n",
    "print(df.iloc[300])\n",
    "```\n",
    "\n",
    "```\n",
    "IndexError: single positional indexer is out-of-bounds\n",
    "```\n",
    "\n",
    "The table has 300 rows, so the last position is 299, or `-1`.\n",
    "\n",
    "| You write | You get |\n",
    "| --- | --- |\n",
    "| `df.iloc[0]` | the first row, as a Series |\n",
    "| `df.iloc[-1]` | the last row |\n",
    "| `df.iloc[2:5]` | the rows at the positions 2, 3, 4 |\n",
    "| `df.iloc[[0, 100, 200]]` | three chosen rows |\n",
    "| `df.iloc[0:3, 0:2]` | the first 3 rows of the first 2 columns |\n",
    "| `df.iloc[0, 4]` | one value |\n",
    "\n",
    "## 7. Choosing rows by label: `loc`\n",
    "\n",
    "`loc` uses labels: the row labels from the index, and the names of the columns. The pattern is `df.loc[row labels, column names]`.\n",
    "\n",
    "### 7.1 A small table with names as labels\n",
    "\n",
    "Change it and run: print Leyla's age."
   ],
   "id": "t10-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "students = pd.DataFrame(\n",
    "    {\"age\": [20, 25, 22, 30], \"grade\": [85.5, 92.0, 78.0, 60.5]},\n",
    "    index=[\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"],\n",
    ")\n",
    "print(students.loc[\"Murad\"])\n",
    "print(students.loc[\"Murad\", \"grade\"])\n",
    "print(students.loc[[\"Aylin\", \"Leyla\"]])"
   ],
   "id": "t10-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`students.loc[\"Murad\"]` is the row with the label Murad. With a column name after the comma you get one value. The age is shown as 25.0 because a row is one Series, and a Series has one type for all its values.\n",
    "\n",
    "### 7.2 A slice with labels includes its end\n",
    "\n",
    "Change it and run: print the rows from Aylin to Leyla with `loc`."
   ],
   "id": "t10-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(students.loc[\"Murad\":\"Kamran\"])\n",
    "print(students.iloc[1:3])"
   ],
   "id": "t10-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`loc[\"Murad\":\"Kamran\"]` gives three rows, with Kamran. `iloc[1:3]` gives two rows, without the position 3.\n",
    "\n",
    "### 7.3 `loc` with the orders\n",
    "\n",
    "In the orders table the row labels are the numbers 0 to 299. Labels and positions look the same here, but `loc` takes the columns by name, which is easier to read:\n",
    "\n",
    "Change it and run: print the `price` and the `units` of the rows 10 to 12."
   ],
   "id": "t10-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.loc[0, \"product\"])\n",
    "print(df.loc[2:4, [\"product\", \"price\"]])\n",
    "print(df.loc[:2, \"customer\":\"category\"])"
   ],
   "id": "t10-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`df.loc[2:4]` gives the rows 2, 3 and 4. A slice of column names works too, and it also includes its end: `\"customer\":\"category\"` takes `customer`, `city` and `category`.\n",
    "\n",
    "### 7.4 When the label and the position are different\n",
    "\n",
    "After sorting, every row keeps its label, but its position changes:\n",
    "\n",
    "Change it and run: sort by `units` instead of `price`. Which row is at the top now, and where is the label 0?"
   ],
   "id": "t10-087"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cheap = df.sort_values(\"price\")\n",
    "print(cheap.head(3))\n",
    "print(cheap.iloc[0][\"price\"])\n",
    "print(cheap.loc[0, \"price\"])"
   ],
   "id": "t10-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`iloc[0]` is the row at the top: the cheapest order. `loc[0]` is the row with the label 0: the first order of the year, wherever it is now.\n",
    "\n",
    "### 7.5 A column as the row labels: `set_index`\n",
    "\n",
    "Change it and run: print all orders of `\"Samir\"`."
   ],
   "id": "t10-089"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "by_customer = df.set_index(\"customer\")\n",
    "print(by_customer.head(3))\n",
    "print(by_customer.loc[\"Sona\", [\"date\", \"product\", \"price\"]])"
   ],
   "id": "t10-090"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`set_index` makes a column the row labels. A label can appear more than once: `loc[\"Sona\"]` gives all rows with this label. `reset_index()` turns the labels back into a normal column.\n",
    "\n",
    "### 7.6 Changing values with `loc`\n",
    "\n",
    "Change it and run: change the city of row 2 to `\"Baku\"`."
   ],
   "id": "t10-091"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.loc[0, \"units\"] = 3\n",
    "df.loc[1, [\"price\", \"units\"]] = [119.0, 2]\n",
    "print(df.head(3))"
   ],
   "id": "t10-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`loc` on the left side of `=` changes the table in memory. The file `orders.csv` stays as it is until you save with `to_csv`.\n",
    "\n",
    "|  | `iloc` | `loc` |\n",
    "| --- | --- | --- |\n",
    "| Uses | positions: 0, 1, 2, ... | row labels and column names |\n",
    "| The end of a slice | not included | included |\n",
    "| One row | `df.iloc[0]` | `df.loc[0]`, `students.loc[\"Murad\"]` |\n",
    "| Rows and columns | `df.iloc[0:3, 0:2]` | `df.loc[0:2, [\"date\", \"customer\"]]` |\n",
    "| One value | `df.iloc[0, 4]` | `df.loc[0, \"product\"]` |\n",
    "| Not found | `IndexError` | `KeyError` |\n",
    "\n",
    "## 8. Sorting\n",
    "\n",
    "### 8.1 By one column\n",
    "\n",
    "Change it and run: sort by `units`, the largest first."
   ],
   "id": "t10-093"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.sort_values(\"price\").head(3))\n",
    "print(df.sort_values(\"price\", ascending=False).head(3))"
   ],
   "id": "t10-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`sort_values` sorts from small to large. With `ascending=False` the largest values come first. Sorting and `head` together answer \"which are the top ...?\".\n",
    "\n",
    "### 8.2 Sorting gives a new table"
   ],
   "id": "t10-095"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.sort_values(\"price\")\n",
    "print(df.head(2))\n",
    "\n",
    "df = df.sort_values(\"price\")\n",
    "print(df.head(2))"
   ],
   "id": "t10-096"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`sort_values` does not change `df`. It gives a sorted copy, and you must store it. Most pandas methods work this way.\n",
    "\n",
    "### 8.3 By two columns\n",
    "\n",
    "Change it and run: sort the prices inside every city from low to high: `ascending=[True, True]`."
   ],
   "id": "t10-097"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "by_city = df.sort_values([\"city\", \"price\"], ascending=[True, False])\n",
    "print(by_city[[\"city\", \"product\", \"price\"]].head(4))"
   ],
   "id": "t10-098"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First by city from A to Z, and inside every city by price, the most expensive first. Text is sorted by the alphabet.\n",
    "\n",
    "### 8.4 The largest and the smallest: `nlargest` and `nsmallest`\n",
    "\n",
    "Change it and run: print the 3 orders with the lowest rating."
   ],
   "id": "t10-099"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(df.nlargest(3, \"units\")[[\"customer\", \"product\", \"units\"]])\n",
    "print(df.nsmallest(2, \"price\")[[\"product\", \"price\"]])"
   ],
   "id": "t10-100"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`nlargest(3, \"units\")` is a short way for \"sort by units, largest first, and take 3\".\n",
    "\n",
    "### 8.5 New row labels after sorting\n",
    "\n",
    "Change it and run: remove `.reset_index(drop=True)`. The old labels come back."
   ],
   "id": "t10-101"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "top = df.sort_values(\"price\", ascending=False).reset_index(drop=True)\n",
    "print(top[[\"product\", \"price\"]].head(3))"
   ],
   "id": "t10-102"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`reset_index(drop=True)` numbers the rows again from 0, so label and position are the same again. `sort_index()` does the opposite: it sorts the rows by their labels, back into the old order.\n",
    "\n",
    "| You write | You get |\n",
    "| --- | --- |\n",
    "| `df.sort_values(\"price\")` | sorted by price, the smallest first |\n",
    "| `df.sort_values(\"price\", ascending=False)` | the largest first |\n",
    "| `df.sort_values([\"city\", \"price\"])` | by city, and inside every city by price |\n",
    "| `df.nlargest(3, \"price\")` | the 3 rows with the highest price |\n",
    "| `df.nsmallest(3, \"price\")` | the 3 rows with the lowest price |\n",
    "| `df.reset_index(drop=True)` | the same rows with new labels 0, 1, 2, ... |\n",
    "| `df.sort_index()` | sorted by the row labels |\n",
    "\n",
    "## 9. New columns and changing columns\n",
    "\n",
    "### 9.1 A new column from a calculation\n",
    "\n",
    "The money of an order is the price times the units. Columns calculate like NumPy arrays, row by row, without a loop:\n",
    "\n",
    "Change it and run: add a second column: `df[\"half\"] = df[\"total\"] / 2`, and print it too."
   ],
   "id": "t10-103"
  },
  {
   "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",
    "print(df[[\"product\", \"price\", \"units\", \"total\"]].head())\n",
    "print(round(df[\"total\"].sum(), 2))"
   ],
   "id": "t10-104"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A new name in the square brackets on the left of `=` creates the column. The last line is the money of the whole year.\n",
    "\n",
    "### 9.2 When a table is too wide\n",
    "\n",
    "Change it and run: add `pd.set_option(\"display.width\", 200)` as the second line. All nine columns are shown."
   ],
   "id": "t10-105"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"total\"] = df[\"price\"] * df[\"units\"]\n",
    "print(df.head(3))"
   ],
   "id": "t10-106"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With nine columns a row is longer than 80 characters, so pandas shortens the table: `...` stands for the columns in the middle, and the last line gives the real size. (In a Jupyter notebook, `print` shows such a table in two pieces instead, one under the other.) Print only the columns you need, as in the example before, or allow longer lines with `pd.set_option(\"display.width\", 200)`.\n",
    "\n",
    "### 9.3 More new columns\n",
    "\n",
    "Change it and run: change the rate from 1.7 to 2."
   ],
   "id": "t10-107"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"currency\"] = \"AZN\"\n",
    "df[\"price_usd\"] = (df[\"price\"] / 1.7).round(2)\n",
    "print(df[[\"product\", \"price\", \"currency\", \"price_usd\"]].head(3))"
   ],
   "id": "t10-108"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One value is put into every row. A calculation can use numbers and other columns, and `.round(2)` rounds every value of a column.\n",
    "\n",
    "### 9.4 Changing a column\n",
    "\n",
    "Change it and run: turn the prices into qepik: `df[\"price\"] = df[\"price\"] * 100`."
   ],
   "id": "t10-109"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"rating\"] = df[\"rating\"] * 20\n",
    "print(df[[\"product\", \"rating\"]].head(3))"
   ],
   "id": "t10-110"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A name that already exists is replaced: the ratings from 1 to 5 are now points from 20 to 100.\n",
    "\n",
    "### 9.5 Renaming columns\n",
    "\n",
    "Change it and run: rename `date` to `day` as well."
   ],
   "id": "t10-111"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "df = df.rename(columns={\"units\": \"quantity\", \"price\": \"unit_price\"})\n",
    "print(df.columns.tolist())"
   ],
   "id": "t10-112"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`rename` takes a dictionary: old name, new name.\n",
    "\n",
    "### 9.6 Removing columns\n",
    "\n",
    "Change it and run: remove only the column `category`."
   ],
   "id": "t10-113"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "df = df.drop(columns=[\"date\", \"rating\"])\n",
    "print(df.head(3))"
   ],
   "id": "t10-114"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 9.7 Converting a type: `astype`"
   ],
   "id": "t10-115"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "df[\"units\"] = df[\"units\"].astype(float)\n",
    "df[\"price\"] = df[\"price\"].astype(int)\n",
    "print(df[[\"product\", \"price\", \"units\"]].head(3))"
   ],
   "id": "t10-116"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`units` is now a decimal, and `price` a whole number. As in NumPy, `astype(int)` cuts off the decimals. It does not round.\n",
    "\n",
    "### 9.8 A copy of a table\n",
    "\n",
    "Change it and run: replace `df.copy()` with `df` and run it again. Both lines print zeros: it was the same table."
   ],
   "id": "t10-117"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(\"orders.csv\")\n",
    "backup = df.copy()\n",
    "df[\"price\"] = 0\n",
    "print(df[\"price\"].head(2).tolist())\n",
    "print(backup[\"price\"].head(2).tolist())"
   ],
   "id": "t10-118"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`df.copy()` is a separate table. Make one before you change data that you may still need.\n",
    "\n",
    "| You write | What it does |\n",
    "| --- | --- |\n",
    "| `df[\"total\"] = df[\"price\"] * df[\"units\"]` | a new column from a calculation |\n",
    "| `df[\"currency\"] = \"AZN\"` | a new column with one value in every row |\n",
    "| `df[\"rating\"] = df[\"rating\"] * 20` | replaces a column |\n",
    "| `df = df.rename(columns={\"units\": \"quantity\"})` | renames a column |\n",
    "| `df = df.drop(columns=[\"date\"])` | removes a column |\n",
    "| `df[\"units\"] = df[\"units\"].astype(float)` | changes the type of a column |\n",
    "| `backup = df.copy()` | a separate copy of the table |\n",
    "\n",
    "## 10. 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",
    "| The file is in another folder, or its name is misspelled | `FileNotFoundError` | check the name and the folder |\n",
    "| A wrong column name: `df[\"City\"]` | `KeyError: 'City'` | names are case-sensitive: look at `df.columns` |\n",
    "| `df[\"city\", \"price\"]` | `KeyError` | a list inside the brackets: `df[[\"city\", \"price\"]]` |\n",
    "| `df[0]` for the first row | `KeyError: 0` | `df.iloc[0]` |\n",
    "| `df.head` without parentheses | a long text about the method, not five rows | `df.head()` |\n",
    "| A column name inside `iloc` | `ValueError` | `iloc` takes positions, `loc` takes names |\n",
    "| Forgetting that a `loc` slice includes its end | one row too many | `df.loc[0:4]` is 5 rows, `df.iloc[0:4]` is 4 |\n",
    "| A position that does not exist: `df.iloc[300]` | `IndexError` | the last position is `len(df) - 1`, or `-1` |\n",
    "| `df.sort_values(\"price\")` without storing it | `df` is not sorted | `df = df.sort_values(\"price\")` |\n",
    "| `df.total = ...` for a new column | no column is created | `df[\"total\"] = ...` |\n",
    "| `to_csv` without `index=False` | an extra column `Unnamed: 0` when the file is read again | `to_csv(\"name.csv\", index=False)` |\n",
    "| `df[\"price\"][0] = 5` | the table is not changed | `df.loc[0, \"price\"] = 5` |\n",
    "\n",
    "A wrong column name:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df[\"City\"])\n",
    "```\n",
    "\n",
    "```\n",
    "KeyError: 'City'\n",
    "```\n",
    "\n",
    "Several columns without the inner list:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df[\"city\", \"price\"])\n",
    "```\n",
    "\n",
    "```\n",
    "KeyError: ('city', 'price')\n",
    "```\n",
    "\n",
    "The first row with square brackets alone:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df[0])\n",
    "```\n",
    "\n",
    "```\n",
    "KeyError: 0\n",
    "```\n",
    "\n",
    "Square brackets alone look for a column with the name 0. Rows need `iloc` or `loc`.\n",
    "\n",
    "A column name inside `iloc`:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.iloc[0, \"city\"])\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: Location based indexing can only have [integer, integer slice (START point is INCLUDED, END point is EXCLUDED), listlike of integers, boolean array] types\n",
    "```\n",
    "\n",
    "Saving without `index=False`:"
   ],
   "id": "t10-119"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "df.head(3).to_csv(\"copy.csv\")\n",
    "print(pd.read_csv(\"copy.csv\").iloc[:, :4])"
   ],
   "id": "t10-120"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The old row labels were saved as a column without a name, and pandas calls it `Unnamed: 0`.\n",
    "\n",
    "## 11. Solved problems (easy to medium-hard)\n",
    "\n",
    "Every example was run, and the outputs are real.\n",
    "\n",
    "### 11.1 Level 1: Easy\n",
    "\n",
    "Problem 1. The warmest day\n",
    "\n",
    "Change it and run: add the temperature 27 for `Sat`."
   ],
   "id": "t10-121"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "temps = pd.Series([18, 22, 25, 19, 16], index=[\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\"])\n",
    "print(temps[\"Wed\"])\n",
    "print(temps.idxmax(), temps.max())\n",
    "print(temps.mean())"
   ],
   "id": "t10-122"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 2. A small table\n",
    "\n",
    "Change it and run: add a fourth city of your choice."
   ],
   "id": "t10-123"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.DataFrame({\n",
    "    \"city\": [\"Baku\", \"Ganja\", \"Shaki\"],\n",
    "    \"population\": [2300000, 335000, 68000],\n",
    "})\n",
    "print(df)\n",
    "print(df.shape)\n",
    "print(df[\"population\"].sum())"
   ],
   "id": "t10-124"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 3. Read the file and look at its size"
   ],
   "id": "t10-125"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(\"Rows:\", df.shape[0])\n",
    "print(\"Columns:\", df.shape[1])\n",
    "print(df.columns.tolist())"
   ],
   "id": "t10-126"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 4. The first and the last orders\n",
    "\n",
    "Change it and run: print the first 10 rows."
   ],
   "id": "t10-127"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df.head(3))\n",
    "print(df.tail(2))"
   ],
   "id": "t10-128"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 5. How many orders in each category?\n",
    "\n",
    "Change it and run: count the cities instead."
   ],
   "id": "t10-129"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(df[\"category\"].value_counts())"
   ],
   "id": "t10-130"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 11.2 Level 2: Medium\n",
    "\n",
    "Problem 6. The most expensive order\n",
    "\n",
    "Change it and run: find the cheapest order instead."
   ],
   "id": "t10-131"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "top = df.sort_values(\"price\", ascending=False).iloc[0]\n",
    "print(top[\"customer\"], \"bought a\", top[\"product\"], \"for\", top[\"price\"])"
   ],
   "id": "t10-132"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: after sorting with the largest first, the row at the position 0 is the most expensive one. It is a Series, so the column names reach its values.\n",
    "\n",
    "Problem 7. Five rows and three columns\n",
    "\n",
    "Change it and run: print the rows 200 to 203."
   ],
   "id": "t10-133"
  },
  {
   "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[100:104, [\"customer\", \"product\", \"price\"]])"
   ],
   "id": "t10-134"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `loc` takes the columns by name, and its slice includes the end: 100 to 104 are five rows.\n",
    "\n",
    "Problem 8. The money of every order\n",
    "\n",
    "Change it and run: print the smallest order too: `df[\"total\"].min()`."
   ],
   "id": "t10-135"
  },
  {
   "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",
    "print(\"Revenue:\", round(df[\"total\"].sum(), 2))\n",
    "print(\"Average order:\", round(df[\"total\"].mean(), 2))\n",
    "print(\"Largest order:\", df[\"total\"].max())"
   ],
   "id": "t10-136"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 9. The five largest orders\n",
    "\n",
    "Change it and run: print the ten largest orders."
   ],
   "id": "t10-137"
  },
  {
   "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",
    "top = df.sort_values(\"total\", ascending=False).head(5)\n",
    "print(top[[\"customer\", \"product\", \"units\", \"total\"]])"
   ],
   "id": "t10-138"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: first the new column, then sorting by it, then `head`. The row labels on the left show where these orders are in the file.\n",
    "\n",
    "Problem 10. The customers\n",
    "\n",
    "Change it and run: print the five customers who ordered most often."
   ],
   "id": "t10-139"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "print(\"Customers:\", df[\"customer\"].nunique())\n",
    "print(df[\"customer\"].value_counts().head(3))"
   ],
   "id": "t10-140"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `nunique` counts the different names. `value_counts` puts the most frequent customers first, so `head(3)` gives the top three.\n",
    "\n",
    "### 11.3 Level 3: Medium-Hard\n",
    "\n",
    "Problem 11. One order, chosen by the user\n",
    "\n",
    "Change it and run: run it with other row numbers, for example `0` and `299`.\n",
    "\n",
    "When the cell asks for input, type `42`."
   ],
   "id": "t10-141"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "42"
     ]
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "position = int(input(\"Row number: \"))\n",
    "row = df.iloc[position]\n",
    "print(row[\"date\"], row[\"customer\"], row[\"product\"])\n",
    "print(\"Total:\", row[\"price\"] * row[\"units\"])"
   ],
   "id": "t10-142"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `iloc` gives the row as a Series, and its values are reached with the column names.\n",
    "\n",
    "Problem 12. Sorted by city, then by price\n",
    "\n",
    "Change it and run: sort the cities from Z to A."
   ],
   "id": "t10-143"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "ordered = df.sort_values([\"city\", \"price\"], ascending=[True, False])\n",
    "print(ordered[[\"city\", \"product\", \"price\"]].head(6))"
   ],
   "id": "t10-144"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 13. How many orders have a rating?\n",
    "\n",
    "Change it and run: do the same for the column `city`."
   ],
   "id": "t10-145"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "rated = df[\"rating\"].count()\n",
    "print(\"With a rating:\", rated)\n",
    "print(\"Without a rating:\", len(df) - rated)\n",
    "print(\"Average rating:\", round(df[\"rating\"].mean(), 2))"
   ],
   "id": "t10-146"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `count` skips the missing values, and `len` counts all rows. The difference is the number of missing ratings.\n",
    "\n",
    "Problem 14. Save the ten largest orders\n",
    "\n",
    "Change it and run: save only the three largest orders."
   ],
   "id": "t10-147"
  },
  {
   "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",
    "top = df.sort_values(\"total\", ascending=False).head(10)\n",
    "top[[\"date\", \"customer\", \"product\", \"total\"]].to_csv(\"top_orders.csv\", index=False)\n",
    "\n",
    "check = pd.read_csv(\"top_orders.csv\")\n",
    "print(check.shape)\n",
    "print(check.head(3))"
   ],
   "id": "t10-148"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the columns are chosen before saving, and `index=False` keeps the old row labels out of the file. Reading the file again shows that it holds 10 rows and 4 columns.\n",
    "\n",
    "Problem 15. A report about a column\n",
    "\n",
    "Change it and run: add `\"total\"` to the list of columns: first create the column, as in problem 8."
   ],
   "id": "t10-149"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "def column_report(df, column):\n",
    "    values = df[column]\n",
    "    print(column, \"| min:\", values.min(), \"| max:\", values.max(), \"| mean:\", round(values.mean(), 2))\n",
    "\n",
    "df = pd.read_csv(\"orders.csv\")\n",
    "for column in [\"price\", \"units\", \"rating\"]:\n",
    "    column_report(df, column)"
   ],
   "id": "t10-150"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the function gets the table and a column name, so the same lines work for every number column.\n",
    "\n",
    "## 14. Quick summary\n",
    "\n",
    "| Concept | What it does | Example |\n",
    "| --- | --- | --- |\n",
    "| `import pandas as pd` | loads pandas | `pd.read_csv(\"orders.csv\")` |\n",
    "| Series | one column of values with labels | `pd.Series([85, 92], index=[\"Aylin\", \"Murad\"])` |\n",
    "| DataFrame | a table of columns | `pd.DataFrame({\"name\": [...], \"age\": [...]})` |\n",
    "| `read_csv` / `to_csv` | reads / saves a CSV file | `df.to_csv(\"new.csv\", index=False)` |\n",
    "| `head` / `tail` | the first / last rows | `df.head(3)` |\n",
    "| `shape` / `dtypes` | size / type of every column | `df.shape` |\n",
    "| `info` / `describe` | a summary / statistics | `df.info()` |\n",
    "| One column | a Series | `df[\"price\"]` |\n",
    "| Several columns | a DataFrame | `df[[\"product\", \"price\"]]` |\n",
    "| `unique` / `nunique` / `value_counts` | different values / how many / how often | `df[\"city\"].value_counts()` |\n",
    "| `iloc` | rows and columns by position | `df.iloc[0:3, 0:2]` |\n",
    "| `loc` | rows and columns by label | `df.loc[0:2, [\"date\", \"price\"]]` |\n",
    "| `set_index` / `reset_index` | a column as row labels / back | `df.set_index(\"customer\")` |\n",
    "| `sort_values` | sorts by a column | `df.sort_values(\"price\", ascending=False)` |\n",
    "| `nlargest` / `nsmallest` | the top / bottom rows | `df.nlargest(3, \"price\")` |\n",
    "| New column | a calculation with whole columns | `df[\"total\"] = df[\"price\"] * df[\"units\"]` |\n",
    "| `rename` / `drop` | renames / removes columns | `df.drop(columns=[\"rating\"])` |\n",
    "\n",
    "Golden rules\n",
    "\n",
    "1. Look first: `head()`, `shape`, `info()`, `describe()`.\n",
    "2. One pair of brackets gives a column, a list inside gives a table: `df[\"price\"]`, `df[[\"price\", \"units\"]]`.\n",
    "3. `iloc` is for positions. `loc` is for labels and column names.\n",
    "4. A `loc` slice includes its end. An `iloc` slice does not.\n",
    "5. Calculate with whole columns, not with loops: `df[\"price\"] * df[\"units\"]`.\n",
    "6. Most methods give a new table. Store the result: `df = df.sort_values(\"price\")`.\n",
    "7. Save with `to_csv(\"name.csv\", index=False)`.\n",
    "\n",
    "Next: the practice notebook (topic-10-practice.ipynb), then Topic 11: Pandas data cleaning and wrangling (missing values, filtering, merging, grouping)."
   ],
   "id": "t10-151"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
