{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 9: NumPy continued: slicing, broadcasting, and vectorized operations\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 5, 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-09-practice.ipynb.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. Slicing a 1D array\n",
    "2. Slicing a 2D array\n",
    "3. A slice is a view, not a copy\n",
    "4. Vectorized operations: arithmetic on whole arrays\n",
    "5. Comparisons give True and False\n",
    "6. Choosing elements with a mask\n",
    "7. Summaries of rows and columns: axis\n",
    "8. Broadcasting\n",
    "9. Common mistakes\n",
    "10. Solved problems (easy to medium-hard)\n",
    "11. Practice problems (try them yourself) (in topic-09-practice.ipynb)\n",
    "12. Check yourself (on the website)\n",
    "13. Quick summary"
   ],
   "id": "t09-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: slicing, vectorized operations and broadcasting\n",
    "\n",
    "What matters most in this lesson. Four things matter most today: cutting rows, columns and blocks out of a table with `table[rows, columns]`; writing a calculation on the whole array instead of a loop; choosing elements with a condition, `a[a > 5]`; and `axis=0` for every column, `axis=1` for every row. Remember also that a slice is a view: changing it changes the original.\n",
    "\n",
    "For broadcasting, a number and one row for every row of a table are enough today. The column case with `reshape(-1, 1)` and the rule become natural with practice. pandas, the next topic, uses all of this every day. There are 15 solved problems. Start with Level 1 and come back for the rest.\n",
    "\n",
    "A beginner-friendly guide to the second half of NumPy. In the last lesson you created arrays and reached single elements by index. In this lesson you take whole parts of an array with slices, calculate with whole arrays at once instead of writing loops, choose elements with a condition, summarise rows and columns, and learn the rule called broadcasting that lets arrays of different shapes work together. 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 how to create an array, what `shape` means, and how to index a 1D and a 2D array (`a[2]`, `table[1, 2]`).\n",
    "\n",
    "## 1. Slicing a 1D array\n",
    "\n",
    "A slice takes a part of an array. It works as with lists: `a[start:stop]`, and the element at `stop` is not included.\n",
    "\n",
    "```\n",
    "values:    [10, 20, 30, 40, 50, 60]\n",
    "index:       0   1   2   3   4   5\n",
    "negative:   -6  -5  -4  -3  -2  -1\n",
    "```\n",
    "\n",
    "Change it and run: print 30 and 40, then the last three elements."
   ],
   "id": "t09-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50, 60])\n",
    "print(a[1:4])\n",
    "print(a[:3])\n",
    "print(a[3:])\n",
    "print(a[-2:])"
   ],
   "id": "t09-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An empty place means \"from the start\" or \"to the end\". `a[:3]` is the first three elements, and `a[-2:]` is the last two.\n",
    "\n",
    "### 1.1 A step\n",
    "\n",
    "The third number is the step: `a[start:stop:step]`.\n",
    "\n",
    "Change it and run: print every third element with `a[::3]`."
   ],
   "id": "t09-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50, 60])\n",
    "print(a[::2])\n",
    "print(a[1::2])\n",
    "print(a[::-1])"
   ],
   "id": "t09-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`a[::2]` takes every second element, and `a[::-1]` gives the array reversed.\n",
    "\n",
    "### 1.2 A slice never gives an IndexError\n",
    "\n",
    "If the numbers are too big, the slice simply stops at the end:\n",
    "\n",
    "Change it and run: try `a[-100:2]`. A start that is too small is no problem either."
   ],
   "id": "t09-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50, 60])\n",
    "print(a[4:100])\n",
    "print(a[10:])"
   ],
   "id": "t09-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.3 Changing a part of an array\n",
    "\n",
    "A slice on the left side of `=` changes all its elements at once:\n",
    "\n",
    "Change it and run: set the first two elements to -1."
   ],
   "id": "t09-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50, 60])\n",
    "a[1:4] = 0\n",
    "print(a)\n",
    "\n",
    "a[-2:] = [7, 8]\n",
    "print(a)"
   ],
   "id": "t09-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One value is put into every place of the slice. A list must have exactly as many items as the slice.\n",
    "\n",
    "| Slice | Meaning |\n",
    "| --- | --- |\n",
    "| `a[1:4]` | from index 1 up to, not including, index 4 |\n",
    "| `a[:3]` | the first 3 elements |\n",
    "| `a[3:]` | from index 3 to the end |\n",
    "| `a[-2:]` | the last 2 elements |\n",
    "| `a[::2]` | every second element |\n",
    "| `a[::-1]` | all elements, reversed |\n",
    "\n",
    "## 2. Slicing a 2D array\n",
    "\n",
    "A 2D array takes two slices, separated by a comma: `table[rows, columns]`. Rows first, then columns, as with indexes.\n",
    "\n",
    "```\n",
    "              column 0   column 1   column 2   column 3\n",
    "   row 0         1          2          3          4\n",
    "   row 1         5          6          7          8\n",
    "   row 2         9         10         11         12\n",
    "```\n",
    "\n",
    "### 2.1 Whole rows\n",
    "\n",
    "Change it and run: print the last row with a slice, `table[2:]`, and with an index, `table[2]`. Count the brackets in the two outputs."
   ],
   "id": "t09-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.arange(1, 13).reshape(3, 4)\n",
    "print(table)\n",
    "print(table[0:2])\n",
    "print(table[1:])"
   ],
   "id": "t09-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With only one slice, you get whole rows.\n",
    "\n",
    "### 2.2 A whole column\n",
    "\n",
    "A colon alone, `:`, means \"all of them\". So `table[:, 1]` reads: all rows, column 1.\n",
    "\n",
    "Change it and run: print column 0, then row 2."
   ],
   "id": "t09-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.arange(1, 13).reshape(3, 4)\n",
    "print(table[:, 1])\n",
    "print(table[:, -1])\n",
    "print(table[1, :])"
   ],
   "id": "t09-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A column comes back as a 1D array. `table[1, :]` is the same as `table[1]`: row 1, all columns.\n",
    "\n",
    "### 2.3 A smaller table\n",
    "\n",
    "Two slices together cut out a block:\n",
    "\n",
    "Change it and run: cut out the bottom right corner: 7, 8, 11, 12."
   ],
   "id": "t09-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.arange(1, 13).reshape(3, 4)\n",
    "print(table[0:2, 1:3])\n",
    "print(table[1:, :2])"
   ],
   "id": "t09-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`table[0:2, 1:3]` means: rows 0 and 1, columns 1 and 2.\n",
    "\n",
    "### 2.4 Several columns, and steps\n",
    "\n",
    "Change it and run: print the last two columns."
   ],
   "id": "t09-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.arange(1, 13).reshape(3, 4)\n",
    "print(table[:, 0:2])\n",
    "print(table[:, ::2])\n",
    "print(table[::-1])"
   ],
   "id": "t09-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`table[::-1]` reverses the order of the rows.\n",
    "\n",
    "### 2.5 The shape of the result\n",
    "\n",
    "An index removes a dimension. A slice keeps it:\n",
    "\n",
    "Change it and run: print the shape of `table[1:, :]` and of `table[1, :]`."
   ],
   "id": "t09-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.arange(1, 13).reshape(3, 4)\n",
    "print(table[:, 1].shape)\n",
    "print(table[:, 1:2].shape)\n",
    "print(table[0:2, 1:3].shape)"
   ],
   "id": "t09-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`table[:, 1]` is a 1D array with 3 elements. `table[:, 1:2]` is still a table, with 3 rows and 1 column.\n",
    "\n",
    "### 2.6 Changing a part of a table\n",
    "\n",
    "Change it and run: set the last column to -1."
   ],
   "id": "t09-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.arange(1, 13).reshape(3, 4)\n",
    "table[:, 0] = 0\n",
    "table[2, 1:] = 99\n",
    "print(table)"
   ],
   "id": "t09-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| You write | You get |\n",
    "| --- | --- |\n",
    "| `table[0:2]` | rows 0 and 1 |\n",
    "| `table[:, 1]` | column 1, as a 1D array |\n",
    "| `table[1, :]` | row 1 (the same as `table[1]`) |\n",
    "| `table[0:2, 1:3]` | a block: rows 0-1, columns 1-2 |\n",
    "| `table[:, :2]` | the first two columns |\n",
    "| `table[::-1]` | the rows in reverse order |\n",
    "| `table[:, 0] = 0` | sets a whole column |\n",
    "\n",
    "## 3. A slice is a view, not a copy\n",
    "\n",
    "This is the biggest difference between arrays and lists. A slice of a list is a new list. A slice of an array is a view: a window onto the same data.\n",
    "\n",
    "Change it and run: change `part[0] = 999` to `part[:] = 0`. Three elements of `a` become 0."
   ],
   "id": "t09-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50])\n",
    "part = a[1:4]\n",
    "part[0] = 999\n",
    "print(part)\n",
    "print(a)"
   ],
   "id": "t09-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We changed `part`, and `a` changed too. NumPy does this on purpose: data sets can be huge, and copying them at every step would be slow.\n",
    "\n",
    "The same with a list, for comparison:"
   ],
   "id": "t09-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = [10, 20, 30, 40, 50]\n",
    "part = numbers[1:4]\n",
    "part[0] = 999\n",
    "print(part)\n",
    "print(numbers)"
   ],
   "id": "t09-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.1 `copy` makes a separate array\n",
    "\n",
    "When you want to change a part without touching the original, add `.copy()`:\n",
    "\n",
    "Change it and run: remove `.copy()` and run it again."
   ],
   "id": "t09-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50])\n",
    "part = a[1:4].copy()\n",
    "part[0] = 999\n",
    "print(part)\n",
    "print(a)"
   ],
   "id": "t09-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 It is the same in 2D\n",
    "\n",
    "Change it and run: add `.copy()` after `table[0]`. The table stays as it was."
   ],
   "id": "t09-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.arange(1, 10).reshape(3, 3)\n",
    "first_row = table[0]\n",
    "first_row[0] = 100\n",
    "print(table)"
   ],
   "id": "t09-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "|  | Gives | Changing it changes the original? |\n",
    "| --- | --- | --- |\n",
    "| A slice, `a[1:4]` | a view | yes |\n",
    "| A row or column, `table[0]`, `table[:, 1]` | a view | yes |\n",
    "| `a[1:4].copy()` | a copy | no |\n",
    "| A list of indexes, `a[[0, 2]]` | a copy | no |\n",
    "| A mask, `a[a > 3]` (Part 6) | a copy | no |\n",
    "\n",
    "## 4. Vectorized operations: arithmetic on whole arrays\n",
    "\n",
    "With a list, a calculation on every item needs a loop. With an array you write the calculation once, and NumPy does it for every element. This is called a vectorized operation.\n",
    "\n",
    "### 4.1 An array and a number\n",
    "\n",
    "Change it and run: print the prices minus 10, and the prices divided by 10."
   ],
   "id": "t09-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "prices = np.array([10, 20, 30, 40])\n",
    "print(prices + 5)\n",
    "print(prices * 2)\n",
    "print(prices / 4)\n",
    "print(prices ** 2)"
   ],
   "id": "t09-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The result is a new array. `prices` itself is not changed. Division always gives decimals.\n",
    "\n",
    "### 4.2 The same with a loop"
   ],
   "id": "t09-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prices = [10, 20, 30, 40]\n",
    "doubled = []\n",
    "for price in prices:\n",
    "    doubled.append(price * 2)\n",
    "print(doubled)"
   ],
   "id": "t09-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Four lines became one: `prices * 2`. The array version is shorter, easier to read, and much faster with large data.\n",
    "\n",
    "### 4.3 Careful: a list behaves differently\n",
    "\n",
    "Change it and run: add `print(numbers + 5)` as the last line and read the error."
   ],
   "id": "t09-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "numbers = [1, 2, 3]\n",
    "print(numbers * 2)\n",
    "print(np.array(numbers) * 2)"
   ],
   "id": "t09-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`* 2` repeats a list, but multiplies an array. `numbers + 5` with a list is even an error. This is one more reason to turn data into an array before calculating.\n",
    "\n",
    "### 4.4 Two arrays\n",
    "\n",
    "When two arrays have the same shape, the operation is done element by element: the first with the first, the second with the second, and so on.\n",
    "\n",
    "Change it and run: change the amounts to `[1, 1, 1]`. What is the total now?"
   ],
   "id": "t09-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "prices = np.array([10, 20, 30])\n",
    "amounts = np.array([2, 1, 4])\n",
    "print(prices + amounts)\n",
    "print(prices * amounts)\n",
    "print((prices * amounts).sum())"
   ],
   "id": "t09-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last line is the total cost of a shopping cart, without a loop.\n",
    "\n",
    "### 4.5 Tables work the same way\n",
    "\n",
    "Change it and run: print `b - a` and `b / a`."
   ],
   "id": "t09-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([\n",
    "    [1, 2],\n",
    "    [3, 4],\n",
    "])\n",
    "b = np.array([\n",
    "    [10, 20],\n",
    "    [30, 40],\n",
    "])\n",
    "print(a + b)\n",
    "print(a * 10)"
   ],
   "id": "t09-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.6 The shapes must fit\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3])\n",
    "b = np.array([10, 20])\n",
    "print(a + b)\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: operands could not be broadcast together with shapes (3,) (2,)\n",
    "```\n",
    "\n",
    "Three elements cannot be paired with two. (Which different shapes do fit is the subject of Part 8.)\n",
    "\n",
    "### 4.7 Changing the array itself\n",
    "\n",
    "`a = a + 5` and `a += 5` both store the result back in `a`:\n",
    "\n",
    "Change it and run: use `a -= 1`, then `a *= 3`."
   ],
   "id": "t09-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3])\n",
    "a += 5\n",
    "print(a)\n",
    "a = a * 2\n",
    "print(a)"
   ],
   "id": "t09-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.8 Math functions for whole arrays\n",
    "\n",
    "NumPy has its own math functions that work on every element:\n",
    "\n",
    "Change it and run: round `c` to 2 decimals, then to 0 decimals."
   ],
   "id": "t09-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 4, 9, 16])\n",
    "print(np.sqrt(a))\n",
    "\n",
    "b = np.array([-3, 2, -1])\n",
    "print(np.abs(b))\n",
    "\n",
    "c = np.array([2.567, 3.141, 9.999])\n",
    "print(np.round(c, 1))"
   ],
   "id": "t09-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Operation | What it does | Example |\n",
    "| --- | --- | --- |\n",
    "| `a + 5`, `a - 5` | adds / subtracts a number from every element | `prices + 5` |\n",
    "| `a * 2`, `a / 2` | multiplies / divides every element | `prices * 2` |\n",
    "| `a ** 2` | the power of every element | `prices ** 2` |\n",
    "| `a + b`, `a * b` | element by element (same shape) | `prices * amounts` |\n",
    "| `np.sqrt(a)` | the square root of every element | `np.sqrt(a)` |\n",
    "| `np.abs(a)` | every element without its minus sign | `np.abs(b)` |\n",
    "| `np.round(a, n)` | every element rounded to `n` decimals | `np.round(c, 1)` |\n",
    "\n",
    "## 5. Comparisons give True and False\n",
    "\n",
    "A comparison is vectorized too. It checks every element and gives an array of `True` and `False`:\n",
    "\n",
    "Change it and run: print which grades are below 50."
   ],
   "id": "t09-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([85, 42, 78, 60, 95])\n",
    "print(grades >= 60)\n",
    "print(grades == 78)"
   ],
   "id": "t09-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Such an array of `True` and `False` is called a boolean mask.\n",
    "\n",
    "### 5.1 Counting with a mask\n",
    "\n",
    "`True` counts as 1 and `False` as 0, so `sum` counts the `True` values:\n",
    "\n",
    "Change it and run: count the grades above 80."
   ],
   "id": "t09-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([85, 42, 78, 60, 95])\n",
    "passed = grades >= 60\n",
    "print(passed.sum())\n",
    "print(passed.mean())"
   ],
   "id": "t09-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "4 students passed. The mean of a mask is the share of `True` values: 0.8 means 80%.\n",
    "\n",
    "### 5.2 `any` and `all`\n",
    "\n",
    "Change it and run: ask whether all grades are at least 50."
   ],
   "id": "t09-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([85, 42, 78, 60, 95])\n",
    "print((grades < 50).any())\n",
    "print((grades >= 40).all())"
   ],
   "id": "t09-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`any` asks \"is at least one True?\", `all` asks \"are all True?\".\n",
    "\n",
    "### 5.3 Comparing two arrays\n",
    "\n",
    "Change it and run: print `second >= first`."
   ],
   "id": "t09-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "first = np.array([70, 80, 90])\n",
    "second = np.array([75, 80, 60])\n",
    "print(second > first)\n",
    "print(first == second)"
   ],
   "id": "t09-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Choosing elements with a mask\n",
    "\n",
    "Put a mask inside the square brackets, and you get only the elements where the mask is `True`. This is called boolean indexing, and it is how data is filtered in NumPy and later in pandas."
   ],
   "id": "t09-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([85, 42, 78, 60, 95])\n",
    "mask = grades >= 60\n",
    "print(mask)\n",
    "print(grades[mask])"
   ],
   "id": "t09-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Usually the condition is written directly inside the brackets:\n",
    "\n",
    "Change it and run: print the grades above 80, then the odd grades."
   ],
   "id": "t09-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([85, 42, 78, 60, 95])\n",
    "print(grades[grades >= 60])\n",
    "print(grades[grades < 50])\n",
    "print(grades[grades % 2 == 0])"
   ],
   "id": "t09-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Read `grades[grades >= 60]` as: \"the grades where the grade is at least 60\".\n",
    "\n",
    "### 6.1 A mask from one array, used on another\n",
    "\n",
    "The two arrays must have the same length:\n",
    "\n",
    "Change it and run: print the names of the students with a grade below 60."
   ],
   "id": "t09-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "names = np.array([\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\", \"Nigar\"])\n",
    "grades = np.array([85, 42, 78, 60, 95])\n",
    "print(names[grades >= 80])"
   ],
   "id": "t09-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.2 Two conditions: `&`, `|` and `~`\n",
    "\n",
    "For arrays, use `&` for \"and\", `|` for \"or\" and `~` for \"not\". Every condition needs its own parentheses:\n",
    "\n",
    "Change it and run: print the grades from 40 to 80, both included."
   ],
   "id": "t09-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([85, 42, 78, 60, 95])\n",
    "print(grades[(grades >= 60) & (grades < 90)])\n",
    "print(grades[(grades < 50) | (grades > 90)])\n",
    "print(grades[~(grades >= 60)])"
   ],
   "id": "t09-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The words `and`, `or` and `not` do not work with arrays:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "grades = np.array([85, 42, 78, 60, 95])\n",
    "print(grades[(grades >= 60) and (grades < 90)])\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\n",
    "```\n",
    "\n",
    "| For single values | For arrays |\n",
    "| --- | --- |\n",
    "| `and` | `&` |\n",
    "| `or` | `\\|` |\n",
    "| `not` | `~` |\n",
    "\n",
    "### 6.3 Changing the chosen elements\n",
    "\n",
    "A mask on the left side of `=` changes only the chosen elements:\n",
    "\n",
    "Change it and run: set every value above 4 to 4."
   ],
   "id": "t09-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "values = np.array([5, -3, 8, -1, 0])\n",
    "values[values < 0] = 0\n",
    "print(values)"
   ],
   "id": "t09-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.4 A mask on a table\n",
    "\n",
    "Change it and run: choose the even numbers of the table."
   ],
   "id": "t09-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.array([\n",
    "    [3, 8, 5],\n",
    "    [12, 7, 10],\n",
    "])\n",
    "print(table > 6)\n",
    "print(table[table > 6])"
   ],
   "id": "t09-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The chosen elements of a table come back as a 1D array.\n",
    "\n",
    "### 6.5 `np.where`: this value or that value\n",
    "\n",
    "`np.where(condition, a, b)` builds a new array: `a` where the condition is `True`, `b` where it is `False`. It is an `if/else` for a whole array.\n",
    "\n",
    "Change it and run: change the pass mark from 60 to 80."
   ],
   "id": "t09-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([85, 42, 78, 60, 95])\n",
    "print(np.where(grades >= 60, \"pass\", \"fail\"))\n",
    "print(np.where(grades > 90, 100, grades))"
   ],
   "id": "t09-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The second line gives 100 to everybody above 90 and keeps the other grades as they are.\n",
    "\n",
    "## 7. Summaries of rows and columns: `axis`\n",
    "\n",
    "You know `sum`, `mean`, `min` and `max` for a whole array. For a table, you often want the result for every column or for every row. The argument `axis` chooses:\n",
    "\n",
    "```\n",
    "                 exam 0   exam 1   exam 2\n",
    "   student 0       80       90       70\n",
    "   student 1       60       50       100\n",
    "\n",
    "   axis=0: down the rows, one result for every column\n",
    "   axis=1: along the columns, one result for every row\n",
    "```\n",
    "\n",
    "Change it and run: add a third student, `[70, 70, 70]`. Which of the three results get longer?"
   ],
   "id": "t09-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([\n",
    "    [80, 90, 70],\n",
    "    [60, 50, 100],\n",
    "])\n",
    "print(grades.sum())\n",
    "print(grades.sum(axis=0))\n",
    "print(grades.sum(axis=1))"
   ],
   "id": "t09-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Without `axis`, the whole table gives one number. With `axis=0`, there is one sum for every column (every exam). With `axis=1`, there is one sum for every row (every student).\n",
    "\n",
    "How to remember it: the axis you name is the one that disappears. The shape is `(2, 3)`. `axis=0` removes the 2, so 3 results are left. `axis=1` removes the 3, so 2 results are left.\n",
    "\n",
    "### 7.1 The other summaries work the same way\n",
    "\n",
    "Change it and run: print the lowest grade of every student."
   ],
   "id": "t09-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([\n",
    "    [80, 90, 70],\n",
    "    [60, 50, 100],\n",
    "])\n",
    "print(grades.mean(axis=0))\n",
    "print(grades.mean(axis=1))\n",
    "print(grades.max(axis=1))\n",
    "print(grades.min(axis=0))"
   ],
   "id": "t09-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.2 `argmax` with an axis\n",
    "\n",
    "Change it and run: print `grades.argmin(axis=1)`: the weakest exam of every student."
   ],
   "id": "t09-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([\n",
    "    [80, 90, 70],\n",
    "    [60, 50, 100],\n",
    "])\n",
    "print(grades.argmax(axis=1))\n",
    "print(grades.argmax(axis=0))"
   ],
   "id": "t09-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first line is the best exam of every student. The second line is the best student of every exam.\n",
    "\n",
    "### 7.3 Sorting\n",
    "\n",
    "`np.sort` gives a sorted copy. The original stays as it is:\n",
    "\n",
    "Change it and run: print the two largest values: `np.sort(a)[::-1][:2]`."
   ],
   "id": "t09-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([30, 10, 50, 20])\n",
    "print(np.sort(a))\n",
    "print(np.sort(a)[::-1])\n",
    "print(a)"
   ],
   "id": "t09-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| You write | You get |\n",
    "| --- | --- |\n",
    "| `table.sum()` | one number for the whole table |\n",
    "| `table.sum(axis=0)` | one result for every column |\n",
    "| `table.sum(axis=1)` | one result for every row |\n",
    "| `mean`, `min`, `max`, `argmax`, `argmin` | take `axis` in the same way |\n",
    "| `np.sort(a)` | a sorted copy |\n",
    "\n",
    "## 8. Broadcasting\n",
    "\n",
    "In Part 4, two arrays needed the same shape. But `prices * 2` worked too, although `2` is a single number. NumPy stretched the 2 so that it fits every element. This stretching is called broadcasting.\n",
    "\n",
    "```\n",
    "   [10, 20, 30] * 2      is calculated like      [10, 20, 30] * [2, 2, 2]\n",
    "```\n",
    "\n",
    "Nothing is really copied. NumPy only behaves as if the small value were repeated.\n",
    "\n",
    "### 8.1 A row and a table\n",
    "\n",
    "A 1D array with as many elements as the table has columns is used for every row:\n",
    "\n",
    "Change it and run: change `row` to `[100, 0, -100]`."
   ],
   "id": "t09-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.array([\n",
    "    [1, 2, 3],\n",
    "    [4, 5, 6],\n",
    "])\n",
    "row = np.array([10, 20, 30])\n",
    "print(table + row)"
   ],
   "id": "t09-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "   [[1, 2, 3],      [10, 20, 30]          [[1, 2, 3],      [[10, 20, 30],\n",
    "    [4, 5, 6]]  +                   ->     [4, 5, 6]]  +    [10, 20, 30]]\n",
    "```\n",
    "\n",
    "### 8.2 A column and a table\n",
    "\n",
    "To use one value for every row, the small array must be a column: a table with one column. `reshape(-1, 1)` makes it:\n",
    "\n",
    "Change it and run: multiply instead of adding: `table * column`."
   ],
   "id": "t09-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.array([\n",
    "    [1, 2, 3],\n",
    "    [4, 5, 6],\n",
    "])\n",
    "column = np.array([100, 200]).reshape(-1, 1)\n",
    "print(column)\n",
    "print(table + column)"
   ],
   "id": "t09-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "100 was added to every element of row 0, and 200 to every element of row 1.\n",
    "\n",
    "### 8.3 The rule\n",
    "\n",
    "Write the two shapes under each other, lined up on the right. Go through the pairs of numbers. The shapes fit when, in every pair, the numbers are equal or one of them is 1. A missing number counts as 1.\n",
    "\n",
    "| First shape | Second shape | Fits? | Why |\n",
    "| --- | --- | --- | --- |\n",
    "| `(2, 3)` | a number | yes | a single number fits everything |\n",
    "| `(2, 3)` | `(3,)` | yes | 3 and 3 are equal |\n",
    "| `(2, 3)` | `(2, 1)` | yes | 3 and 1: one of them is 1. 2 and 2 are equal |\n",
    "| `(2, 3)` | `(2,)` | no | 3 and 2 are different, and none is 1 |\n",
    "| `(3,)` | `(2,)` | no | 3 and 2 are different |\n",
    "\n",
    "The size 1 is the one that gets stretched.\n",
    "\n",
    "### 8.4 When the shapes do not fit\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "table = np.array([\n",
    "    [1, 2, 3],\n",
    "    [4, 5, 6],\n",
    "])\n",
    "values = np.array([100, 200])\n",
    "print(table + values)\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: operands could not be broadcast together with shapes (2,3) (2,)\n",
    "```\n",
    "\n",
    "The table has 3 columns, and `values` has 2 elements. NumPy lines shapes up on the right, so it tries to use `values` as a row, and that does not fit. The fix is the column from above: `values.reshape(-1, 1)`.\n",
    "\n",
    "### 8.5 What broadcasting is used for\n",
    "\n",
    "Subtracting the mean of every column from that column, in one line:\n",
    "\n",
    "Change it and run: subtract the largest grade of every exam instead: `grades.max(axis=0)`."
   ],
   "id": "t09-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([\n",
    "    [80, 90, 70],\n",
    "    [60, 50, 100],\n",
    "    [70, 70, 70],\n",
    "])\n",
    "means = grades.mean(axis=0)\n",
    "print(means)\n",
    "print(grades - means)"
   ],
   "id": "t09-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`grades` has the shape `(3, 3)` and `means` has the shape `(3,)`: one mean for every column, used for every row. The result shows how far every grade is from the average of its exam. You will see this step again and again in machine learning.\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",
    "| Expecting a slice to be a copy | changing the slice changes the original | `a[1:4].copy()` |\n",
    "| Thinking the stop index is included | one element is missing | `a[1:4]` gives the indexes 1, 2, 3 |\n",
    "| `table[1][:2]` instead of `table[1, :2]` | works here, but fails for columns | one pair of brackets: `table[rows, columns]` |\n",
    "| `table[:][1]` for a column | you get row 1, not column 1 | `table[:, 1]` |\n",
    "| `and` / `or` between masks | `ValueError`: the truth value is ambiguous | `&` and `\\|` |\n",
    "| No parentheses around the conditions | `ValueError`, or a wrong result | `(a > 2) & (a < 5)` |\n",
    "| `if a > 5:` with a whole array | `ValueError`: the truth value is ambiguous | `(a > 5).any()` or `(a > 5).all()` |\n",
    "| Arrays with shapes that do not fit | `ValueError`: could not be broadcast | check both `shape`s first |\n",
    "| Mixing up `axis=0` and `axis=1` | results for columns instead of rows | `axis=0`: for every column. `axis=1`: for every row |\n",
    "| `numbers * 2` with a list | the list is repeated | make it an array first |\n",
    "| A list of the wrong length into a slice | `ValueError` | as many items as the slice has |\n",
    "| A mask of another length | `IndexError` | the mask must come from an array of the same length |\n",
    "\n",
    "A column with the wrong brackets:"
   ],
   "id": "t09-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.arange(1, 13).reshape(3, 4)\n",
    "print(table[:][1])\n",
    "print(table[:, 1])"
   ],
   "id": "t09-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`table[:]` is the whole table, and `[1]` then takes row 1. Only `table[:, 1]` is the column.\n",
    "\n",
    "Conditions without parentheses:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3, 4, 5, 6])\n",
    "print(a[a > 2 & a < 5])\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\n",
    "```\n",
    "\n",
    "`&` is calculated before `>` and `<`, so Python reads this in a way nobody wanted. Write `a[(a > 2) & (a < 5)]`.\n",
    "\n",
    "`if` with a whole array:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "a = np.array([3, 8, 5])\n",
    "if a > 5:\n",
    "    print(\"large\")\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()\n",
    "```\n",
    "\n",
    "`a > 5` is three answers, and `if` needs one. Say which one you mean: `(a > 5).any()` or `(a > 5).all()`.\n",
    "\n",
    "A list of the wrong length into a slice:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50])\n",
    "a[1:4] = [7, 8]\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: could not broadcast input array from shape (2,) into shape (3,)\n",
    "```\n",
    "\n",
    "A mask of another length:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50])\n",
    "mask = np.array([True, False, True])\n",
    "print(a[mask])\n",
    "```\n",
    "\n",
    "```\n",
    "IndexError: boolean index did not match indexed array along axis 0; size of axis is 5 but size of corresponding boolean axis is 3\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 first three and the last three\n",
    "\n",
    "Change it and run: print the elements 4, 5, 6 and 7."
   ],
   "id": "t09-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.arange(1, 11)\n",
    "print(a[:3])\n",
    "print(a[-3:])"
   ],
   "id": "t09-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 2. Every element doubled\n",
    "\n",
    "Change it and run: print half of every element."
   ],
   "id": "t09-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([4, 8, 15, 16, 23, 42])\n",
    "print(a * 2)"
   ],
   "id": "t09-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 3. The even numbers\n",
    "\n",
    "Change it and run: print the numbers that can be divided by 3."
   ],
   "id": "t09-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.arange(1, 11)\n",
    "print(a[a % 2 == 0])"
   ],
   "id": "t09-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 4. One column of a table\n",
    "\n",
    "Change it and run: print the last row, then the last column."
   ],
   "id": "t09-087"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.arange(1, 13).reshape(3, 4)\n",
    "print(table)\n",
    "print(table[:, 2])"
   ],
   "id": "t09-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 5. Celsius to Fahrenheit\n",
    "\n",
    "Change it and run: add -40 to the list. At -40 both scales show the same number."
   ],
   "id": "t09-089"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "celsius = np.array([0, 10, 25, 37, 100])\n",
    "fahrenheit = celsius * 9 / 5 + 32\n",
    "print(fahrenheit)"
   ],
   "id": "t09-090"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the formula is written once, and NumPy applies it to every temperature.\n",
    "\n",
    "### 10.2 Level 2: Medium\n",
    "\n",
    "Problem 6. How many passed, and who?\n",
    "\n",
    "Change it and run: change the pass mark to 50."
   ],
   "id": "t09-091"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "names = np.array([\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\", \"Nigar\"])\n",
    "grades = np.array([85, 42, 78, 55, 95])\n",
    "\n",
    "passed = grades >= 60\n",
    "print(\"Passed:\", passed.sum())\n",
    "print(names[passed])\n",
    "print(\"Average of those who passed:\", grades[passed].mean())"
   ],
   "id": "t09-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the mask is made once and used three times: for counting, on the names, and on the grades.\n",
    "\n",
    "Problem 7. The total price of a cart\n",
    "\n",
    "Change it and run: set every amount to 1."
   ],
   "id": "t09-093"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "prices = np.array([1.5, 0.8, 2.0, 4.0])\n",
    "amounts = np.array([2, 5, 1, 3])\n",
    "\n",
    "costs = prices * amounts\n",
    "print(costs)\n",
    "print(\"Total:\", costs.sum())"
   ],
   "id": "t09-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 8. A 20% discount on expensive products\n",
    "\n",
    "Change it and run: make the discount 50%."
   ],
   "id": "t09-095"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "prices = np.array([40, 120, 75, 200, 90])\n",
    "new_prices = np.where(prices > 100, prices * 0.8, prices)\n",
    "print(new_prices)"
   ],
   "id": "t09-096"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `np.where` takes the discounted price where the condition is true, and the old price everywhere else.\n",
    "\n",
    "Problem 9. Negative numbers become zero\n",
    "\n",
    "Change it and run: remove `.copy()` and look at the last line."
   ],
   "id": "t09-097"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "values = np.array([4, -2, 7, -9, 0, 3])\n",
    "cleaned = values.copy()\n",
    "cleaned[cleaned < 0] = 0\n",
    "print(cleaned)\n",
    "print(values)"
   ],
   "id": "t09-098"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the copy keeps the original data safe. Without `.copy()`, `cleaned` and `values` would be the same array.\n",
    "\n",
    "Problem 10. The average of every student and of every exam\n",
    "\n",
    "Change it and run: round both results to 1 decimal: `np.round(grades.mean(axis=1), 1)`."
   ],
   "id": "t09-099"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([\n",
    "    [85, 90, 78],\n",
    "    [92, 60, 88],\n",
    "    [70, 75, 95],\n",
    "])\n",
    "print(\"Students:\", grades.mean(axis=1))\n",
    "print(\"Exams:\", grades.mean(axis=0))"
   ],
   "id": "t09-100"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: each row is a student, so `axis=1` gives one average for every row. Each column is an exam, so `axis=0` gives one average for every column.\n",
    "\n",
    "### 10.3 Level 3: Medium-Hard\n",
    "\n",
    "Problem 11. The best student by average\n",
    "\n",
    "Change it and run: change one of Murad's grades to 100."
   ],
   "id": "t09-101"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "names = np.array([\"Aylin\", \"Murad\", \"Leyla\"])\n",
    "grades = np.array([\n",
    "    [85, 90, 78],\n",
    "    [92, 60, 88],\n",
    "    [70, 75, 95],\n",
    "])\n",
    "averages = grades.mean(axis=1)\n",
    "best = averages.argmax()\n",
    "print(np.round(averages, 1))\n",
    "print(names[best], \"has the best average\")"
   ],
   "id": "t09-102"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 12. Values between two limits\n",
    "\n",
    "Change it and run: change the limits to 10 and 20."
   ],
   "id": "t09-103"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "temps = np.array([12, 25, 31, 18, 22, 35, 8])\n",
    "nice = temps[(temps >= 18) & (temps <= 25)]\n",
    "print(nice)\n",
    "print(nice.size, \"nice days\")"
   ],
   "id": "t09-104"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: two conditions joined with `&`, each in its own parentheses.\n",
    "\n",
    "Problem 13. Every number as a share of the total\n",
    "\n",
    "Change it and run: add a fourth sale, 1000."
   ],
   "id": "t09-105"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "sales = np.array([200, 300, 500])\n",
    "shares = sales / sales.sum() * 100\n",
    "print(shares)"
   ],
   "id": "t09-106"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `sales.sum()` is a single number, so it is broadcast to every element.\n",
    "\n",
    "Problem 14. A bonus for every exam\n",
    "\n",
    "Each row is a student, each column an exam. Exam 0 gets 5 extra points, exam 1 gets 0 and exam 2 gets 10. No grade may be above 100.\n",
    "\n",
    "Change it and run: give every exam 10 extra points: `bonus = 10`."
   ],
   "id": "t09-107"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([\n",
    "    [85, 90, 78],\n",
    "    [92, 60, 95],\n",
    "])\n",
    "bonus = np.array([5, 0, 10])\n",
    "\n",
    "new_grades = grades + bonus\n",
    "new_grades[new_grades > 100] = 100\n",
    "print(new_grades)"
   ],
   "id": "t09-108"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `bonus` has one value for every column, so broadcasting uses it for every row. The mask then cuts the grades that went above 100.\n",
    "\n",
    "Problem 15. How far is every grade from the student's own average?\n",
    "\n",
    "Change it and run: subtract the average of every exam instead: `axis=0`, and no `reshape`."
   ],
   "id": "t09-109"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([\n",
    "    [80, 90, 70],\n",
    "    [60, 50, 100],\n",
    "])\n",
    "averages = grades.mean(axis=1).reshape(-1, 1)\n",
    "print(averages)\n",
    "print(grades - averages)"
   ],
   "id": "t09-110"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: there is one average for every row, so it must be a column with the shape `(2, 1)`. Then it is broadcast across the three exams of each student.\n",
    "\n",
    "## 13. Quick summary\n",
    "\n",
    "| Concept | What it does | Example |\n",
    "| --- | --- | --- |\n",
    "| 1D slice | a part of an array | `a[1:4]`, `a[::-1]` |\n",
    "| 2D slice | rows, then columns | `table[0:2, 1:3]` |\n",
    "| `:` alone | all rows or all columns | `table[:, 1]` |\n",
    "| View | a slice shares its data with the original | `part = a[1:4]` |\n",
    "| `copy` | a separate array | `a[1:4].copy()` |\n",
    "| Vectorized operation | a calculation on every element, no loop | `prices * 2`, `a + b` |\n",
    "| `np.sqrt`, `np.abs`, `np.round` | math on every element | `np.round(c, 1)` |\n",
    "| Comparison | an array of `True` and `False` | `grades >= 60` |\n",
    "| Mask | chooses the elements where it is `True` | `grades[grades >= 60]` |\n",
    "| `&`, `\\|`, `~` | and, or, not for masks | `(a > 2) & (a < 5)` |\n",
    "| `np.where` | this value or that value | `np.where(a > 0, a, 0)` |\n",
    "| `axis=0` / `axis=1` | one result for every column / every row | `table.sum(axis=0)` |\n",
    "| `np.sort` | a sorted copy | `np.sort(a)` |\n",
    "| Broadcasting | a smaller shape is stretched to fit | `table + row` |\n",
    "\n",
    "Golden rules\n",
    "\n",
    "1. Rows first, then columns: `table[rows, columns]`. A colon alone means \"all\".\n",
    "2. A slice is a view. Use `.copy()` when the original must stay as it is.\n",
    "3. Do not loop over an array for a calculation. Write the calculation on the whole array.\n",
    "4. A condition on an array gives a mask. The mask in square brackets chooses the elements.\n",
    "5. Use `&`, `|` and `~` between masks, with parentheses around every condition.\n",
    "6. `axis=0` gives one result for every column, `axis=1` one for every row.\n",
    "7. Shapes fit when, lined up on the right, the numbers are equal or one of them is 1.\n",
    "\n",
    "Next: the practice notebook (topic-09-practice.ipynb), then Topic 10: Pandas fundamentals: Series and DataFrames, reading data."
   ],
   "id": "t09-111"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
