{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 8: NumPy fundamentals: arrays and indexing\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 4, 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-08-practice.ipynb.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. NumPy and the first arrays\n",
    "2. The properties of an array\n",
    "3. Ready-made arrays\n",
    "4. Data types\n",
    "5. Indexing: one element\n",
    "6. Several elements at once: a list of indexes\n",
    "7. Changing the shape: reshape\n",
    "8. Loops, summaries and copying\n",
    "9. Common mistakes\n",
    "10. Solved problems (easy to medium-hard)\n",
    "11. Practice problems (try them yourself) (in topic-08-practice.ipynb)\n",
    "12. Check yourself (on the website)\n",
    "13. Quick summary"
   ],
   "id": "t08-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction: NumPy arrays and indexing\n",
    "\n",
    "What matters most in this lesson. Four things matter most today: creating an array with `np.array` and reading its `shape`; knowing that all items of an array have one type; reaching one element with `a[i]` in a 1D array and with `table[row, column]` in a 2D array, row first; and taking several elements with a list of indexes.\n",
    "\n",
    "`linspace`, `eye`, random numbers and `reshape` come back in many later lessons, so a first look is enough today. Slicing and calculations on whole arrays without loops are the next lesson. There are 15 solved problems. Start with Level 1 and come back for the rest.\n",
    "\n",
    "A beginner-friendly guide to NumPy, the library that almost all Data Science in Python is built on. It starts from the simplest examples and gets harder step by step: what an array is and how it differs from a list, how to create arrays, what their properties and data types are, and how to reach and change single elements with indexes in one and two dimensions. 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, loops, functions and how to import a module.\n",
    "\n",
    "This lesson and the next one. This lesson is about creating arrays and reaching elements by index. The next lesson continues with slicing, broadcasting and calculations on whole arrays without loops. Those topics are left out here on purpose.\n",
    "\n",
    "## 1. NumPy and the first arrays\n",
    "\n",
    "### 1.1 What is NumPy?\n",
    "\n",
    "NumPy (Numerical Python) is a package for working with numbers in arrays. An array is a grid of values, like a list or a table, but built for calculation. pandas, Matplotlib and scikit-learn all store their data in NumPy arrays, so everything in the rest of this course stands on it.\n",
    "\n",
    "### 1.2 Importing NumPy\n",
    "\n",
    "NumPy is not part of Python itself. With Anaconda it is already installed. Everybody imports it with the short name `np`:"
   ],
   "id": "t08-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "print(np.__version__)"
   ],
   "id": "t08-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.3 The first array\n",
    "\n",
    "`np.array(...)` turns a list into an array:\n",
    "\n",
    "Change it and run: add two more grades to the list."
   ],
   "id": "t08-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([85, 92, 78, 60, 95])\n",
    "print(grades)\n",
    "print(type(grades))"
   ],
   "id": "t08-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice two things. The array is printed without commas. And its type is `ndarray`, which means \"n-dimensional array\".\n",
    "\n",
    "### 1.4 Why not just a list?\n",
    "\n",
    "|  | List | NumPy array |\n",
    "| --- | --- | --- |\n",
    "| Types of the items | any mix | one type for all items |\n",
    "| Made for | general collections | numbers and calculation |\n",
    "| Dimensions | a list of lists for a table | real rows and columns |\n",
    "| Size | can grow (`append`) | fixed when created |\n",
    "| Speed with many numbers | slow | fast |\n",
    "\n",
    "An array gives up flexibility (one type, fixed size) and gets speed and a clear shape in return.\n",
    "\n",
    "### 1.5 An array from a list: one dimension\n",
    "\n",
    "Change it and run: put your own numbers into `a`."
   ],
   "id": "t08-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3, 4])\n",
    "b = np.array([2.5, 10.0, 7.25])\n",
    "print(a)\n",
    "print(b)"
   ],
   "id": "t08-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.6 An array from a list of lists: two dimensions\n",
    "\n",
    "A list of lists becomes an array with rows and columns. Every inner list is one row:\n",
    "\n",
    "Change it and run: add a third row, `[7, 8, 9]`."
   ],
   "id": "t08-007"
  },
  {
   "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",
    "print(table)"
   ],
   "id": "t08-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All rows must have the same length. This is a real table, not just lists inside a list.\n",
    "\n",
    "### 1.7 The square brackets are required\n",
    "\n",
    "`np.array` takes one list. Forgetting the brackets is a very common mistake:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "a = np.array(1, 2, 3)\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: array() takes from 1 to 2 positional arguments but 3 were given\n",
    "```\n",
    "\n",
    "### 1.8 One type for all items\n",
    "\n",
    "If the list mixes whole numbers and decimals, NumPy converts everything to decimals:\n",
    "\n",
    "Change it and run: change `3.5` to `3`. The dots disappear, because every item is a whole number now."
   ],
   "id": "t08-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "mixed = np.array([1, 2, 3.5])\n",
    "print(mixed)"
   ],
   "id": "t08-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`1.` and `2.` are the decimals 1.0 and 2.0. NumPy prints them in this short way.\n",
    "\n",
    "If the list contains a text, everything becomes text. Calculations are then impossible:\n",
    "\n",
    "Change it and run: change `\"three\"` to `3`. The quotes disappear."
   ],
   "id": "t08-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "mixed = np.array([1, 2, \"three\"])\n",
    "print(mixed)"
   ],
   "id": "t08-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.9 From an array back to a list"
   ],
   "id": "t08-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3])\n",
    "print(a.tolist())\n",
    "print(type(a.tolist()))"
   ],
   "id": "t08-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. The properties of an array\n",
    "\n",
    "Every array knows four things about itself:\n",
    "\n",
    "| Property | Meaning | Example for a table with 2 rows and 3 columns |\n",
    "| --- | --- | --- |\n",
    "| `ndim` | the number of dimensions | `2` |\n",
    "| `shape` | the size in each dimension, as a tuple | `(2, 3)` |\n",
    "| `size` | the total number of items | `6` |\n",
    "| `dtype` | the data type of the items | `int64` |\n",
    "\n",
    "They are attributes, so they are written without parentheses.\n",
    "\n",
    "Change it and run: add a fifth number to the list. Which of the four lines change?"
   ],
   "id": "t08-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40])\n",
    "print(a.ndim)\n",
    "print(a.shape)\n",
    "print(a.size)\n",
    "print(a.dtype)"
   ],
   "id": "t08-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`(4,)` is a tuple with one item: one dimension with 4 items.\n",
    "\n",
    "On your computer (Anaconda, Jupyter) and in Colab, whole numbers in an array are `int64`. If you run this notebook on the Asiman Data School website, or with an older NumPy on Windows, the same line shows `int32`. Both are types for whole numbers, and nothing else in this lesson changes.\n",
    "\n",
    "Change it and run: add a third row, `[7, 8, 9]`. Predict `shape` and `size` before you run it."
   ],
   "id": "t08-017"
  },
  {
   "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",
    "print(table.ndim)\n",
    "print(table.shape)\n",
    "print(table.size)\n",
    "print(table.dtype)"
   ],
   "id": "t08-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How to read a shape: `(2, 3)` means 2 rows and 3 columns. Rows always come first.\n",
    "\n",
    "### 2.1 `len` gives the number of rows\n",
    "\n",
    "Change it and run: add a third row and run it again."
   ],
   "id": "t08-019"
  },
  {
   "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",
    "print(len(table))\n",
    "print(table.shape[0], table.shape[1])"
   ],
   "id": "t08-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For a 2D array, `len` is the number of rows, not the number of items. `shape[0]` is the number of rows and `shape[1]` the number of columns.\n",
    "\n",
    "## 3. Ready-made arrays\n",
    "\n",
    "Often you need an array of a certain size before you have the data.\n",
    "\n",
    "### 3.1 `zeros`, `ones`, `full`\n",
    "\n",
    "Change it and run: make 10 zeros, and an array of six 3s."
   ],
   "id": "t08-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "print(np.zeros(4))\n",
    "print(np.ones(3))\n",
    "print(np.full(5, 7))"
   ],
   "id": "t08-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For two dimensions, give the shape as a tuple `(rows, columns)`:\n",
    "\n",
    "Change it and run: make a table of ones with 3 rows and 5 columns."
   ],
   "id": "t08-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "print(np.zeros((2, 3)))\n",
    "print(np.full((2, 2), 9))"
   ],
   "id": "t08-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`zeros` and `ones` make decimals (`0.`, `1.`) unless you ask for another type (Part 4).\n",
    "\n",
    "### 3.2 `arange`: like `range`, but an array\n",
    "\n",
    "Change it and run: print the even numbers from 0 to 20, with 20 included."
   ],
   "id": "t08-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "print(np.arange(5))\n",
    "print(np.arange(2, 10))\n",
    "print(np.arange(0, 20, 5))\n",
    "print(np.arange(0, 1, 0.25))"
   ],
   "id": "t08-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The rules are the same as for `range`: start, stop (not included), step. Unlike `range`, the step can be a decimal.\n",
    "\n",
    "### 3.3 `linspace`: a fixed number of evenly spaced values\n",
    "\n",
    "Change it and run: change the count in the first line from 5 to 11."
   ],
   "id": "t08-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "print(np.linspace(0, 1, 5))\n",
    "print(np.linspace(0, 100, 3))"
   ],
   "id": "t08-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`linspace(start, stop, count)` gives exactly `count` values, and the stop value is included.\n",
    "\n",
    "|  | `arange(start, stop, step)` | `linspace(start, stop, count)` |\n",
    "| --- | --- | --- |\n",
    "| You choose | the step | how many values |\n",
    "| Stop value | not included | included |\n",
    "\n",
    "### 3.4 `eye`: the identity matrix\n",
    "\n",
    "Change it and run: change 3 to 5."
   ],
   "id": "t08-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "print(np.eye(3))"
   ],
   "id": "t08-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ones on the diagonal, zeros elsewhere. You will meet it again in linear algebra.\n",
    "\n",
    "### 3.5 Random numbers\n",
    "\n",
    "Random arrays are used all the time, for test data and in machine learning. The values are different on every run, so the output is not shown here:\n",
    "\n",
    "Change it and run: run it several times. The numbers are different each time."
   ],
   "id": "t08-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "print(np.random.randint(1, 7, 5))      # 5 whole numbers from 1 to 6\n",
    "print(np.random.rand(3))               # 3 decimals between 0 and 1\n",
    "print(np.random.rand(2, 3))            # 2 rows, 3 columns"
   ],
   "id": "t08-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Function | What it makes | Example |\n",
    "| --- | --- | --- |\n",
    "| `np.array(list)` | an array from a list | `np.array([1, 2, 3])` |\n",
    "| `np.zeros(shape)` | all zeros | `np.zeros((2, 3))` |\n",
    "| `np.ones(shape)` | all ones | `np.ones(4)` |\n",
    "| `np.full(shape, value)` | one value everywhere | `np.full(5, 7)` |\n",
    "| `np.arange(start, stop, step)` | numbers with a step | `np.arange(0, 20, 5)` |\n",
    "| `np.linspace(start, stop, count)` | a number of evenly spaced values | `np.linspace(0, 1, 5)` |\n",
    "| `np.eye(n)` | the identity matrix | `np.eye(3)` |\n",
    "| `np.random.randint(low, high, count)` | random whole numbers | `np.random.randint(1, 7, 5)` |\n",
    "\n",
    "## 4. Data types\n",
    "\n",
    "All items of an array have the same type, called the dtype.\n",
    "\n",
    "| dtype | Meaning | Example |\n",
    "| --- | --- | --- |\n",
    "| `int64` | whole numbers | `np.array([1, 2, 3])` |\n",
    "| `float64` | decimals | `np.array([1.5, 2.0])` |\n",
    "| `bool` | `True` and `False` | `np.array([True, False])` |\n",
    "| `<U...` | text | `np.array([\"a\", \"b\"])` |"
   ],
   "id": "t08-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "print(np.array([1, 2, 3]).dtype)\n",
    "print(np.array([1.5, 2.0]).dtype)\n",
    "print(np.array([True, False]).dtype)\n",
    "print(np.array([\"red\", \"green\"]).dtype)"
   ],
   "id": "t08-034"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`<U5` means text with up to 5 characters. The number `64` in `int64` is the size of each number in memory, in bits.\n",
    "\n",
    "### 4.1 Choosing the type: `dtype=`\n",
    "\n",
    "Change it and run: change `dtype=float` to `dtype=str`."
   ],
   "id": "t08-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3], dtype=float)\n",
    "b = np.zeros(3, dtype=int)\n",
    "print(a)\n",
    "print(b)"
   ],
   "id": "t08-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.2 Converting: `astype`\n",
    "\n",
    "`astype` makes a new array with another type:\n",
    "\n",
    "Change it and run: change `2.9` to `-2.9`. The result is -2, not -3: the decimal part is cut off."
   ],
   "id": "t08-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "prices = np.array([2.9, 10.5, 7.1])\n",
    "whole = prices.astype(int)\n",
    "print(whole)\n",
    "print(prices)\n",
    "\n",
    "texts = np.array([\"10\", \"20\", \"30\"])\n",
    "numbers = texts.astype(int)\n",
    "print(numbers)\n",
    "print(numbers.dtype)"
   ],
   "id": "t08-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Converting decimals to `int` cuts off the decimal part. It does not round. The original array is not changed.\n",
    "\n",
    "### 4.3 A trap: a decimal stored in an array of whole numbers\n",
    "\n",
    "Change it and run: add `dtype=float` to the first line: `np.array([1, 2, 3], dtype=float)`."
   ],
   "id": "t08-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3])\n",
    "a[0] = 9.9\n",
    "print(a)"
   ],
   "id": "t08-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The array has the type `int64`, so 9.9 was cut to 9 without any warning. If you need decimals, create the array with `dtype=float`.\n",
    "\n",
    "### 4.4 One element is a NumPy number\n",
    "\n",
    "One element of an array is not a Python `int`. It is a NumPy number with the type of the array:\n",
    "\n",
    "Change it and run: change the list to `[1.5, 2.5, 3.5]` and look at the type again."
   ],
   "id": "t08-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30])\n",
    "print(a[0] + 5)\n",
    "print(type(a[0]))\n",
    "print([a[0], a[1]])\n",
    "print(a.tolist())"
   ],
   "id": "t08-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It calculates and prints like a normal number. Only inside a list, a tuple or a dictionary does Python show its full name, `np.int64(10)`. When you need plain Python numbers, use `a.tolist()` for the whole array, or `int(a[0])` for one element.\n",
    "\n",
    "## 5. Indexing: one element\n",
    "\n",
    "### 5.1 Indexing a 1D array\n",
    "\n",
    "Indexing works as with lists: square brackets, and counting starts at 0.\n",
    "\n",
    "```\n",
    "values:    [10, 20, 30, 40, 50]\n",
    "index:       0   1   2   3   4\n",
    "negative:   -5  -4  -3  -2  -1\n",
    "```\n",
    "\n",
    "Change it and run: print the element 30 in two ways: with a positive and with a negative index."
   ],
   "id": "t08-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50])\n",
    "print(a[0])\n",
    "print(a[2])\n",
    "print(a[-1])\n",
    "print(a[-2])"
   ],
   "id": "t08-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An index that does not exist is an error:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50])\n",
    "print(a[5])\n",
    "```\n",
    "\n",
    "```\n",
    "IndexError: index 5 is out of bounds for axis 0 with size 5\n",
    "```\n",
    "\n",
    "\"Axis 0\" is the first (and here the only) dimension.\n",
    "\n",
    "### 5.2 Changing an element\n",
    "\n",
    "Arrays are mutable, like lists:\n",
    "\n",
    "Change it and run: set the middle element to 0."
   ],
   "id": "t08-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50])\n",
    "a[0] = 99\n",
    "a[-1] = a[-1] + 1\n",
    "print(a)"
   ],
   "id": "t08-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.3 The size is fixed\n",
    "\n",
    "An array has no `append` method. Its size is set when it is created:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30])\n",
    "a.append(40)\n",
    "```\n",
    "\n",
    "```\n",
    "AttributeError: 'numpy.ndarray' object has no attribute 'append'\n",
    "```\n",
    "\n",
    "`np.append(a, 40)` exists, but it builds a new array each time. Collect values in a list first, and convert the list to an array at the end.\n",
    "\n",
    "### 5.4 Indexing a 2D array\n",
    "\n",
    "A 2D array needs two indexes: the row, then the column, separated by a comma.\n",
    "\n",
    "```\n",
    "              column 0   column 1   column 2\n",
    "   row 0         1          2          3\n",
    "   row 1         4          5          6\n",
    "   row 2         7          8          9\n",
    "```\n",
    "\n",
    "Change it and run: print the 8, then the 6."
   ],
   "id": "t08-047"
  },
  {
   "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",
    "    [7, 8, 9],\n",
    "])\n",
    "print(table[0, 0])\n",
    "print(table[1, 2])\n",
    "print(table[2, 0])\n",
    "print(table[-1, -1])"
   ],
   "id": "t08-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`table[1, 2]` means: row 1, column 2. Row first, then column.\n",
    "\n",
    "### 5.5 One index gives a whole row\n",
    "\n",
    "Change it and run: print the middle row."
   ],
   "id": "t08-049"
  },
  {
   "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",
    "    [7, 8, 9],\n",
    "])\n",
    "print(table[0])\n",
    "print(table[-1])\n",
    "print(table[1].shape)"
   ],
   "id": "t08-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A row of a 2D array is a 1D array.\n",
    "\n",
    "### 5.6 `table[1, 2]` or `table[1][2]`?\n",
    "\n",
    "Both give the same element. The first form is the NumPy way: it is shorter, and it is the form that the next lesson builds on."
   ],
   "id": "t08-051"
  },
  {
   "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",
    "print(table[1, 2])\n",
    "print(table[1][2])"
   ],
   "id": "t08-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.7 Changing elements and whole rows\n",
    "\n",
    "Change it and run: change the 5 in the middle to 0."
   ],
   "id": "t08-053"
  },
  {
   "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",
    "    [7, 8, 9],\n",
    "])\n",
    "table[0, 0] = 100\n",
    "table[2] = [0, 0, 0]\n",
    "print(table)"
   ],
   "id": "t08-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.8 An index out of range\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "table = np.array([\n",
    "    [1, 2, 3],\n",
    "    [4, 5, 6],\n",
    "])\n",
    "print(table[0, 3])\n",
    "```\n",
    "\n",
    "```\n",
    "IndexError: index 3 is out of bounds for axis 1 with size 3\n",
    "```\n",
    "\n",
    "The message tells you which axis is wrong: axis 0 is the rows, axis 1 is the columns.\n",
    "\n",
    "| You write | You get |\n",
    "| --- | --- |\n",
    "| `table[1, 2]` | one element: row 1, column 2 |\n",
    "| `table[1]` | the whole row 1, as a 1D array |\n",
    "| `table[-1, -1]` | the last element of the last row |\n",
    "| `table[1, 2] = 0` | changes one element |\n",
    "| `table[1] = [0, 0, 0]` | changes a whole row |\n",
    "\n",
    "## 6. Several elements at once: a list of indexes\n",
    "\n",
    "Instead of one index you can give a list of indexes. The result is a new array with those elements, in the order you asked for:\n",
    "\n",
    "Change it and run: print 50, 30, 10, in this order."
   ],
   "id": "t08-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50])\n",
    "print(a[[0, 2, 4]])\n",
    "print(a[[4, 0]])\n",
    "print(a[[1, 1, 1]])"
   ],
   "id": "t08-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice the double brackets: the outer ones are the indexing, the inner ones are the list.\n",
    "\n",
    "The list can be stored in a variable, or be another array:\n",
    "\n",
    "Change it and run: change `winners` to `[3, 1, 0]`."
   ],
   "id": "t08-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "names = np.array([\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"])\n",
    "winners = [2, 0]\n",
    "print(names[winners])"
   ],
   "id": "t08-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.1 Rows of a 2D array\n",
    "\n",
    "Change it and run: print the rows in the opposite order: the last, the middle, the first."
   ],
   "id": "t08-059"
  },
  {
   "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",
    "    [7, 8, 9],\n",
    "])\n",
    "print(table[[0, 2]])"
   ],
   "id": "t08-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.2 Chosen elements of a 2D array\n",
    "\n",
    "With two lists, NumPy takes them in pairs: the first row index with the first column index, and so on.\n",
    "\n",
    "Change it and run: take the other diagonal: 3, 5, 7."
   ],
   "id": "t08-061"
  },
  {
   "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",
    "    [7, 8, 9],\n",
    "])\n",
    "print(table[[0, 1, 2], [0, 1, 2]])\n",
    "print(table[[0, 2], [2, 0]])"
   ],
   "id": "t08-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first line takes the elements at (0, 0), (1, 1) and (2, 2): the diagonal.\n",
    "\n",
    "### 6.3 Changing several elements\n",
    "\n",
    "Change it and run: set the elements 20 and 40 to -1."
   ],
   "id": "t08-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50])\n",
    "a[[0, 4]] = 0\n",
    "print(a)"
   ],
   "id": "t08-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Changing the shape: `reshape`\n",
    "\n",
    "`reshape` arranges the same items in another shape. The number of items must stay the same.\n",
    "\n",
    "Change it and run: reshape to 1 row and 6 columns, then to 6 rows and 1 column."
   ],
   "id": "t08-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.arange(1, 7)\n",
    "print(a)\n",
    "\n",
    "table = a.reshape(2, 3)\n",
    "print(table)\n",
    "print(table.shape)"
   ],
   "id": "t08-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The items fill the new shape row by row."
   ],
   "id": "t08-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.arange(1, 7)\n",
    "print(a.reshape(3, 2))"
   ],
   "id": "t08-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.1 `-1`: let NumPy calculate one size\n",
    "\n",
    "Change it and run: change `reshape(3, -1)` to `reshape(2, -1)`, then to `reshape(5, -1)`. The last one fails: 12 items cannot fill 5 equal rows."
   ],
   "id": "t08-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.arange(12)\n",
    "print(a.reshape(3, -1))\n",
    "print(a.reshape(-1, 6).shape)"
   ],
   "id": "t08-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`-1` means \"whatever fits\". With 12 items and 3 rows, NumPy finds 4 columns.\n",
    "\n",
    "### 7.2 The sizes must match\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "a = np.arange(6)\n",
    "print(a.reshape(4, 2))\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: cannot reshape array of size 6 into shape (4,2)\n",
    "```\n",
    "\n",
    "### 7.3 Back to one dimension: `flatten`"
   ],
   "id": "t08-071"
  },
  {
   "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",
    "print(table.flatten())"
   ],
   "id": "t08-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`arange` and `reshape` together are the quickest way to make a test table:\n",
    "\n",
    "Change it and run: make a table with 4 rows and 3 columns from the same numbers."
   ],
   "id": "t08-073"
  },
  {
   "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, 1])"
   ],
   "id": "t08-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Loops, summaries and copying\n",
    "\n",
    "### 8.1 A loop over a 1D array\n",
    "\n",
    "Change it and run: change the pass mark from 50 to 80."
   ],
   "id": "t08-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([85, 42, 78, 60])\n",
    "for grade in grades:\n",
    "    if grade >= 50:\n",
    "        print(grade, \"passed\")\n",
    "    else:\n",
    "        print(grade, \"failed\")"
   ],
   "id": "t08-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.2 A loop over a 2D array gives the rows\n",
    "\n",
    "Change it and run: print the last item of each row instead."
   ],
   "id": "t08-077"
  },
  {
   "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",
    "for row in table:\n",
    "    print(row, \"first item:\", row[0])"
   ],
   "id": "t08-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.3 Every element with its indexes\n",
    "\n",
    "Change it and run: add a third row to the table. The loops need no change."
   ],
   "id": "t08-079"
  },
  {
   "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",
    "for i in range(table.shape[0]):\n",
    "    for j in range(table.shape[1]):\n",
    "        print(i, j, table[i, j])"
   ],
   "id": "t08-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`shape[0]` rows and `shape[1]` columns give the two ranges.\n",
    "\n",
    "(In the next lesson you will see that most calculations on arrays need no loop at all. Loops are shown here because they make the indexes visible.)\n",
    "\n",
    "### 8.4 Simple summaries\n",
    "\n",
    "An array can summarise itself:\n",
    "\n",
    "Change it and run: add the grade 0 to the array. Which results change?"
   ],
   "id": "t08-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "grades = np.array([85, 92, 78, 60, 95])\n",
    "print(grades.sum())\n",
    "print(grades.mean())\n",
    "print(grades.min(), grades.max())"
   ],
   "id": "t08-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`argmax` and `argmin` give the index of the largest and the smallest element. With the index you can look into another array:\n",
    "\n",
    "Change it and run: change Murad's grade to 99."
   ],
   "id": "t08-083"
  },
  {
   "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, 92, 78, 60, 95])\n",
    "\n",
    "best = grades.argmax()\n",
    "print(best)\n",
    "print(names[best], grades[best])\n",
    "print(names[grades.argmin()])"
   ],
   "id": "t08-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.5 Copying an array\n",
    "\n",
    "As with lists, `b = a` does not copy. It gives the same array a second name:"
   ],
   "id": "t08-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3])\n",
    "b = a\n",
    "b[0] = 100\n",
    "print(a)"
   ],
   "id": "t08-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`.copy()` makes a real, separate array:\n",
    "\n",
    "Change it and run: change `b = a.copy()` back to `b = a` and compare."
   ],
   "id": "t08-087"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3])\n",
    "b = a.copy()\n",
    "b[0] = 100\n",
    "print(a)\n",
    "print(b)"
   ],
   "id": "t08-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 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",
    "| `np.array(1, 2, 3)` | `TypeError` | one list: `np.array([1, 2, 3])` |\n",
    "| Forgetting `import numpy as np` | `NameError: name 'np' is not defined` | import it at the top |\n",
    "| `a.shape()` with parentheses | `TypeError`: a tuple is not callable | `a.shape` is an attribute |\n",
    "| `np.zeros(2, 3)` | `TypeError` | the shape is one tuple: `np.zeros((2, 3))` |\n",
    "| Rows of different lengths | `ValueError` | every row needs the same number of items |\n",
    "| Index out of range | `IndexError` | the last index is `size - 1`, or use `-1` |\n",
    "| Column first, then row | the wrong element, or `IndexError` | row first: `table[row, column]` |\n",
    "| `a.append(x)` | `AttributeError` | arrays have a fixed size: build a list first |\n",
    "| A decimal stored in an `int` array | the decimal part is cut off silently | create the array with `dtype=float` |\n",
    "| `reshape` to a shape that does not fit | `ValueError` | rows × columns must equal `size` |\n",
    "| `b = a` to copy | both names change together | `b = a.copy()` |\n",
    "| `a[0, 2, 4]` for several elements | `IndexError`: too many indices | a list inside: `a[[0, 2, 4]]` |\n",
    "\n",
    "`shape` with parentheses:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "a = np.array([1, 2, 3])\n",
    "print(a.shape())\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: 'tuple' object is not callable\n",
    "```\n",
    "\n",
    "Rows of different lengths:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "table = np.array([\n",
    "    [1, 2, 3],\n",
    "    [4, 5],\n",
    "])\n",
    "```\n",
    "\n",
    "```\n",
    "ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.\n",
    "```\n",
    "\n",
    "Several elements without the inner list:\n",
    "\n",
    "```python\n",
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50])\n",
    "print(a[0, 2, 4])\n",
    "```\n",
    "\n",
    "```\n",
    "IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed\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. Create an array and look at it"
   ],
   "id": "t08-089"
  },
  {
   "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)\n",
    "print(a.shape, a.size, a.dtype)"
   ],
   "id": "t08-090"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 2. First, last and middle element\n",
    "\n",
    "Change it and run: add a sixth number, 60. Which element is the middle one now?"
   ],
   "id": "t08-091"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.array([10, 20, 30, 40, 50])\n",
    "print(a[0])\n",
    "print(a[-1])\n",
    "print(a[a.size // 2])"
   ],
   "id": "t08-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 3. The numbers from 1 to 10\n",
    "\n",
    "Change it and run: make the numbers from 1 to 100 and print their sum."
   ],
   "id": "t08-093"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "a = np.arange(1, 11)\n",
    "print(a)\n",
    "print(a.sum())"
   ],
   "id": "t08-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 4. A table of zeros with one value changed\n",
    "\n",
    "Change it and run: set the four corners of the table to 1."
   ],
   "id": "t08-095"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.zeros((3, 4), dtype=int)\n",
    "table[1, 2] = 5\n",
    "print(table)"
   ],
   "id": "t08-096"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 5. One element of a table\n",
    "\n",
    "Change it and run: print the 25."
   ],
   "id": "t08-097"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.array([\n",
    "    [5, 10, 15],\n",
    "    [20, 25, 30],\n",
    "])\n",
    "print(table[0, 1])\n",
    "print(table[1, -1])\n",
    "print(table.shape)"
   ],
   "id": "t08-098"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 10.2 Level 2: Medium\n",
    "\n",
    "Problem 6. An array from user input\n",
    "\n",
    "Change it and run: run it with other numbers, for example `3 9 2`.\n",
    "\n",
    "When the cell asks for input, type `4 8 15 16`."
   ],
   "id": "t08-099"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "4 8 15 16"
     ]
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "numbers = np.array(list(map(int, input().split())))\n",
    "print(numbers)\n",
    "print(numbers.size, numbers.sum(), numbers.max())"
   ],
   "id": "t08-100"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the input line becomes a list of numbers (as in the lesson about lists), and `np.array` turns the list into an array.\n",
    "\n",
    "Problem 7. The four corners of a table\n",
    "\n",
    "Change it and run: change the shape to `reshape(4, 3)`. The same line still prints the corners."
   ],
   "id": "t08-101"
  },
  {
   "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, 0], table[0, -1], table[-1, 0], table[-1, -1])"
   ],
   "id": "t08-102"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: negative indexes work in each dimension, so the corners need no knowledge of the size.\n",
    "\n",
    "Problem 8. The best student\n",
    "\n",
    "Change it and run: change Kamran's grade to 99."
   ],
   "id": "t08-103"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "names = np.array([\"Aylin\", \"Murad\", \"Leyla\", \"Kamran\"])\n",
    "grades = np.array([85, 92, 78, 45])\n",
    "\n",
    "best = grades.argmax()\n",
    "print(names[best], grades[best])\n",
    "print(\"Average:\", grades.mean())"
   ],
   "id": "t08-104"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `argmax` gives a position, and the same position is used in both arrays.\n",
    "\n",
    "Problem 9. Chosen students\n",
    "\n",
    "Change it and run: choose the students at the indexes 1 and 3."
   ],
   "id": "t08-105"
  },
  {
   "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, 92, 78, 45, 66])\n",
    "\n",
    "chosen = [0, 2, 4]\n",
    "print(names[chosen])\n",
    "print(grades[chosen])\n",
    "print(grades[chosen].mean())"
   ],
   "id": "t08-106"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 10. Decimals to whole numbers"
   ],
   "id": "t08-107"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "prices = np.array([2.9, 10.5, 7.1, 3.99])\n",
    "whole = prices.astype(int)\n",
    "print(whole)\n",
    "print(whole.dtype)\n",
    "print(prices.sum(), whole.sum())"
   ],
   "id": "t08-108"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `astype(int)` cuts off the decimals, so the sum of the whole numbers is smaller.\n",
    "\n",
    "### 10.3 Level 3: Medium-Hard\n",
    "\n",
    "Problem 11. The sum of every row, with loops\n",
    "\n",
    "Change it and run: add a fourth row, `[10, 11, 12]`."
   ],
   "id": "t08-109"
  },
  {
   "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",
    "    [7, 8, 9],\n",
    "])\n",
    "for i in range(table.shape[0]):\n",
    "    total = 0\n",
    "    for j in range(table.shape[1]):\n",
    "        total = total + table[i, j]\n",
    "    print(\"Row\", i, \"sum:\", total)"
   ],
   "id": "t08-110"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: two loops, one for the rows and one for the columns, and `table[i, j]` reaches each element. (The next lesson does this in one line.)\n",
    "\n",
    "Problem 12. The diagonal of a square table\n",
    "\n",
    "Change it and run: print the other diagonal (4, 7, 10, 13). The columns are then `[3, 2, 1, 0]`."
   ],
   "id": "t08-111"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.arange(1, 17).reshape(4, 4)\n",
    "print(table)\n",
    "\n",
    "positions = list(range(4))\n",
    "print(table[positions, positions])"
   ],
   "id": "t08-112"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the diagonal elements are (0, 0), (1, 1), (2, 2), (3, 3). Two equal lists of indexes take them in pairs.\n",
    "\n",
    "Problem 13. Swap the first and the last row\n",
    "\n",
    "Change it and run: swap the first and the middle row."
   ],
   "id": "t08-113"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "table = np.arange(1, 10).reshape(3, 3)\n",
    "table[[0, -1]] = table[[-1, 0]]\n",
    "print(table)"
   ],
   "id": "t08-114"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the right side takes the rows in the order (last, first), and the left side stores them at (first, last).\n",
    "\n",
    "Problem 14. Count the even numbers in a table\n",
    "\n",
    "Change it and run: count the odd numbers instead."
   ],
   "id": "t08-115"
  },
  {
   "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",
    "count = 0\n",
    "for row in table:\n",
    "    for value in row:\n",
    "        if value % 2 == 0:\n",
    "            count = count + 1\n",
    "print(\"Even numbers:\", count)"
   ],
   "id": "t08-116"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 15. A grade table\n",
    "\n",
    "Each row is a student, each column an exam. Print the best exam of every student.\n",
    "\n",
    "Change it and run: change one of Murad's grades to 100."
   ],
   "id": "t08-117"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "names = [\"Aylin\", \"Murad\", \"Leyla\"]\n",
    "grades = np.array([\n",
    "    [85, 90, 78],\n",
    "    [92, 60, 88],\n",
    "    [70, 75, 95],\n",
    "])\n",
    "\n",
    "for i in range(len(names)):\n",
    "    row = grades[i]\n",
    "    best = row.argmax()\n",
    "    print(names[i], \"- best exam:\", best + 1, \"with\", row[best])"
   ],
   "id": "t08-118"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `grades[i]` is the row of one student. `argmax` gives the position of the best grade in that row, and `+ 1` turns the index into an exam number.\n",
    "\n",
    "## 13. Quick summary\n",
    "\n",
    "| Concept | What it does | Example |\n",
    "| --- | --- | --- |\n",
    "| `import numpy as np` | loads NumPy | `np.array([1, 2, 3])` |\n",
    "| Array | a grid of values of one type | `np.array([[1, 2], [3, 4]])` |\n",
    "| `ndim` / `shape` / `size` | dimensions / size per dimension / number of items | `table.shape` gives `(2, 3)` |\n",
    "| `dtype` | the type of the items | `int64`, `float64` |\n",
    "| `zeros` / `ones` / `full` | arrays filled with one value | `np.zeros((2, 3))` |\n",
    "| `arange` | numbers with a step | `np.arange(0, 20, 5)` |\n",
    "| `linspace` | a number of evenly spaced values | `np.linspace(0, 1, 5)` |\n",
    "| `astype` | a new array with another type | `prices.astype(int)` |\n",
    "| 1D index | one element | `a[0]`, `a[-1]` |\n",
    "| 2D index | row, then column | `table[1, 2]` |\n",
    "| One index on a 2D array | a whole row | `table[1]` |\n",
    "| A list of indexes | several elements at once | `a[[0, 2, 4]]` |\n",
    "| `reshape` | the same items in another shape | `a.reshape(3, 4)` |\n",
    "| `sum` / `mean` / `min` / `max` | simple summaries | `grades.mean()` |\n",
    "| `argmax` / `argmin` | the index of the largest / smallest | `names[grades.argmax()]` |\n",
    "| `copy` | a separate array | `b = a.copy()` |\n",
    "\n",
    "Golden rules\n",
    "\n",
    "1. `np.array` takes one list: `np.array([1, 2, 3])`.\n",
    "2. An array has one type for all its items, and a fixed size.\n",
    "3. Check `shape` first. For a 2D array it is `(rows, columns)`.\n",
    "4. Row first, then column: `table[row, column]`.\n",
    "5. Several elements need a list inside the brackets: `a[[0, 2, 4]]`.\n",
    "6. `reshape` keeps the number of items: rows × columns must equal `size`.\n",
    "7. `b = a` is not a copy. Use `a.copy()`.\n",
    "\n",
    "Next: the practice notebook (topic-08-practice.ipynb), then Topic 9: NumPy continued: slicing, broadcasting, and vectorized operations."
   ],
   "id": "t08-119"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
