{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "eeb8b201",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "skip"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# You'll start seeing this cell in most lectures.\n",
    "# It exists to hide all of the import statements and other setup\n",
    "# code we need in lecture notebooks.\n",
    "from dsc80_utils import *"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3143de48",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# Lecture 2 – DataFrame Fundamentals\n",
    "\n",
    "## DSC 80, Winter 2025"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a0d867d",
   "metadata": {
    "editable": true,
    "jp-MarkdownHeadingCollapsed": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Announcements 📣\n",
    "\n",
    "- Lab 1 is released, and is due **Wednesday, January 15 at 11:59pm**.\n",
    "    - See the [Tech Support](https://dsc80.com/tech_support/) page for instructions and watch [this video 🎥](https://www.loom.com/share/0ea254b85b2745e59322b5e5a8692e91?sid=d64a6a06-b2ca-4290-babc-be6666425d09) for tips on how to set up your environment and work on assignments.\n",
    "    - Please try to set up your computer ASAP so that you have enough time to debug your environment.\n",
    "- Project 1 will be released by Wednesday.\n",
    "- Please fill out the [Welcome Survey](https://forms.gle/uYGK8tFj8EygXmERA) **ASAP**.\n",
    "- Lecture recordings are available [here](https://podcast.ucsd.edu), and are linked on the course website."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5a4afdd4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Agenda\n",
    "\n",
    "- `numpy` arrays.\n",
    "- From `babypandas` to `pandas`.\n",
    "    - Deep dive into DataFrames.\n",
    "- Accessing subsets of rows and columns in DataFrames.\n",
    "    - `.loc` and `.iloc`.\n",
    "    - Querying (i.e. filtering).\n",
    "- Adding and modifying columns.\n",
    "- `pandas` and `numpy`.\n",
    "    \n",
    "We can't cover every single detail! The [`pandas` documentation](https://pandas.pydata.org/docs/user_guide/index.html#user-guide) will be your friend."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "50e5db5f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "<div class=\"alert alert-warning\">\n",
    "    <h3>Question 🤔 (Answer using `lec02-dog`)</h3>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7f4b593",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs = pd.read_csv('data/dogs43.csv')\n",
    "dogs.head(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "520ceee8",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "**What does this code do?**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11978ecf",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "whoa = np.random.choice([True, False], size=len(dogs))\n",
    "(dogs[whoa]\n",
    " .groupby('size')\n",
    " .max()\n",
    " .get('longevity')\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aaecf86a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## `numpy` arrays"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4dc9df4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "### `numpy` overview\n",
    "\n",
    "- `numpy` stands for \"numerical Python\". It is a commonly-used Python module that enables **fast** computation involving arrays and matrices.\n",
    "- `numpy`'s main object is the **array**. In `numpy`, arrays are:\n",
    "    - Homogenous – all values are of the same type.\n",
    "    - (Potentially) multi-dimensional.\n",
    "- Computation in `numpy` is fast because:\n",
    "    - Much of it is implemented in C.\n",
    "    - `numpy` arrays are stored more efficiently in memory than, say, Python lists. \n",
    "- [This site](https://cloudxlab.com/blog/numpy-pandas-introduction/) provides a good overview of `numpy` arrays.\n",
    "\n",
    "We used `numpy` in DSC 10 to work with sequences of data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80a82e41",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "arr = np.arange(10)\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed29adc4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# The shape (10,) means that the array only has a single dimension,\n",
    "# of size 10.\n",
    "arr.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "de9f257f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "2 ** arr"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84a43343",
   "metadata": {},
   "source": [
    "Arrays come equipped with several handy methods; some examples are below, but you can read about them all [here](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "df2ec76f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "(2 ** arr).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77dfc0a2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "(2 ** arr).mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eabeecaf",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "(2 ** arr).max()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca4bab47",
   "metadata": {
    "editable": true,
    "scrolled": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "(2 ** arr).argmax()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eb19cca8",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "### ⚠️ The dangers of `for`-loops\n",
    "\n",
    "- `for`-loops are slow when processing large datasets. **You will rarely write `for`-loops in DSC 80 (except for Lab 1 and Project 1), and may be penalized on assignments for using them when unnecessary!**\n",
    "- One of the biggest benefits of `numpy` is that it supports **vectorized** operations. \n",
    "    - If `a` and `b` are two arrays of the same length, then `a + b` is a new array of the same length containing the element-wise sum of `a` and `b`.\n",
    "- To illustrate how much faster `numpy` arithmetic is than using a `for`-loop, let's compute the squares of the numbers between 0 and 1,000,000:\n",
    "    - Using a `for`-loop.\n",
    "    - Using vectorized arithmetic, through `numpy`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f0c5235",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "%%timeit\n",
    "squares = []\n",
    "for i in range(1_000_000):\n",
    "    squares.append(i * i)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1c026a9",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "In vanilla Python, this takes about 0.04 seconds per loop."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1dae0772",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "%%timeit\n",
    "squares = np.arange(1_000_000) ** 2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "07b6d506",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "In `numpy`, this only takes about 0.001 seconds per loop, more than 40x faster! Note that under the hood, `numpy` is also using a `for`-loop, but it's a `for`-loop implemented in C, which is much faster than Python."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b602e6e6",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "### Multi-dimensional arrays\n",
    "\n",
    "While we didn't see these very often in DSC 10, multi-dimensional lists/arrays may have since come up in DSC 20, 30, or 40A (especially in the context of linear algebra).\n",
    "\n",
    "We'll spend a bit of time talking about 2D (and 3D) arrays here, since in some ways, they behave similarly to DataFrames. \n",
    "\n",
    "Below, we create a 2D array from scratch."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96fdb9b9",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "nums = np.array([\n",
    "    [5, 1, 9, 7],\n",
    "    [9, 8, 2, 3],\n",
    "    [2, 5, 0, 4]\n",
    "])\n",
    "\n",
    "nums"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6fa8e7e4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# nums has 3 rows and 4 columns.\n",
    "nums.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78f49585",
   "metadata": {},
   "source": [
    "We can also create 2D arrays by _reshaping_ other arrays."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b5574e1d",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Here, we're asking to reshape np.arange(1, 7)\n",
    "# so that it has 2 rows and 3 columns.\n",
    "a = np.arange(1, 7).reshape((2, 3))\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18337230",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "### Operations along axes\n",
    "\n",
    "In 2D arrays (and DataFrames), axis 0 refers to the rows (up and down) and axis 1 refers to the columns (left and right).\n",
    "\n",
    "<center><img src='imgs/axis-sum.png' width=600></center>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "926e7e95",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b4c93a42",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "If we specify `axis=0`, `a.sum` will \"compress\" along axis 0."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94995957",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "a.sum(axis=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d58fb1b3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "If we specify `axis=1`, `a.sum` will \"compress\" along axis 1."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8a251862",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "a.sum(axis=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "718f6fbc",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "source": [
    "### Selecting rows and columns from 2D arrays"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46b5b4b2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "You can use `[`square brackets`]` to **slice** rows and columns out of an array, using the same slicing conventions you saw in DSC 20."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6934d0fa",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb2e554b",
   "metadata": {
    "editable": true,
    "scrolled": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Accesses row 0 and all columns.\n",
    "a[0, :]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65e4fdcf",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Same as the above.\n",
    "a[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "195f2e35",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Accesses all rows and column 1.\n",
    "a[:, 1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a049722",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Accesses row 0 and columns 1 and onwards.\n",
    "a[0, 1:]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "919f52a6",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "<div class=\"alert alert-warning\">\n",
    "    <h3>Question 🤔 (Answer at `lec02-grid`)</h3>\n",
    "        \n",
    "Try and predict the value of <code>grid[-1, 1:].sum()</code> without running the code below.\n",
    "\n",
    "<b>See if <a href=\"https://chat.openai.com/\">ChatGPT</a> can do it.</b>\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a385d42",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "s = (5, 3)\n",
    "grid = np.ones(s) * 2 * np.arange(1, 16).reshape(s)\n",
    "# grid[-1, 1:].sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b4b36a2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Example: Image processing\n",
    "\n",
    "`numpy` arrays are homogenous and potentially multi-dimensional.\n",
    "\n",
    "It turns out that **images** can be represented as 3D `numpy` arrays. The color of each pixel can be described with three numbers under the RGB model – a red value, green value, and blue value. Each of these can vary from 0 to 1.\n",
    "\n",
    "<center><img src='imgs/three_d_array.png' width=250><small>(<a href=\"https://e2eml.school/convert_rgb_to_grayscale\">image source</a>)</small></center>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ef1666f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from PIL import Image\n",
    "img_path = Path('imgs') / 'bentley.jpg'\n",
    "img = np.asarray(Image.open(img_path)) / 255"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c3c05170",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "img"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "405c5f82",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "img.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80128938",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "plt.imshow(img)\n",
    "plt.axis('off');"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c6b0383",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Applying a greyscale filter\n",
    "\n",
    "One way to convert an image to greyscale is to average its red, green, and blue values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59d5a3a3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "mean_2d = img.mean(axis=2)\n",
    "mean_2d"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16f3f8ba",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "This is just a single red channel!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "773e9aa3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "plt.imshow(mean_2d)\n",
    "plt.axis('off');"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad0bed73",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "We need to _repeat_ `mean_2d` three times along axis 2, to use the same values for the red, green, and blue channels. `np.repeat` will help us here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a6b025bf",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# np.newaxis is an alias for None.\n",
    "# It helps us introduce an additional axis.\n",
    "np.arange(5)[:, np.newaxis]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e0a6db8",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "np.repeat(np.arange(5)[:, np.newaxis], 3, axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "841a0699",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "mean_3d = np.repeat(mean_2d[:, :, np.newaxis], 3, axis=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eee2cf26",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "plt.imshow(mean_3d)\n",
    "plt.axis('off');"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2633b72",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Applying a sepia filter\n",
    "\n",
    "Let's sepia-fy Junior!\n",
    "\n",
    "<center>\n",
    "<img src=\"imgs/apple-sepia.png\" width=50%>\n",
    "    <small>\n",
    "(<a href=\"https://support.apple.com/guide/motion/sepia-filter-motn169f8c87/mac\">Image credits</a>)</small>\n",
    "</center>\n",
    "\n",
    "From [here](https://stackoverflow.com/questions/1061093/how-is-a-sepia-tone-created), we can apply this conversion to each pixel.\n",
    "\n",
    "$$\\begin{align*}\n",
    "R_{\\text{sepia}} &= 0.393R + 0.769G + 0.189B \\\\ G_{\\text{sepia}} &= 0.349R + 0.686G + 0.168B \\\\\n",
    "B_{\\text{sepia}} &= 0.272R + 0.534G + 0.131B\\end{align*}$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0be87f2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "sepia_filter = np.array([\n",
    "    [0.393, 0.769, 0.189],\n",
    "    [0.349, 0.686, 0.168],\n",
    "    [0.272, 0.534, 0.131]\n",
    "])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9ed3e3f5",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Multiplies each pixel by the sepia_filter matrix.\n",
    "# Then, clips each RGB value to be between 0 and 1.\n",
    "filtered = (img @ sepia_filter.T).clip(0, 1)\n",
    "filtered"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d58c595",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "plt.imshow(filtered)\n",
    "plt.axis('off');"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e091cbf4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Key takeaway: avoid `for`-loops whenever possible!\n",
    "\n",
    "You can do a lot without `for`-loops, both in `numpy` and in `pandas`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "018d58fd",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## From `babypandas` to `pandas` 🐼"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "420e9507",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### `babypandas`\n",
    "\n",
    "In DSC 10, you used `babypandas`, which was a subset of `pandas` designed to be friendly for beginners.\n",
    "<center><img src='imgs/babypanda.jpg' width=45%></center>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8412e023",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### pandas\n",
    "\n",
    "You're not a beginner anymore – you've taken DSC 20, 30, and 40A. You're ready for the real deal.\n",
    "\n",
    "<center><img src='imgs/angrypanda.jpg' width=60%></center>\n",
    "\n",
    "Fortunately, **everything you learned in `babypandas` will carry over!**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a7137020",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### `pandas`\n",
    "\n",
    "<center><img src='imgs/pandas.png' width=200></center>\n",
    "\n",
    "- `pandas` is **the** Python library for tabular data manipulation.\n",
    "- Before `pandas` was developed, the standard data science workflow involved using multiple languages (Python, R, Java) in a single project.\n",
    "- Wes McKinney, the original developer of `pandas`, wanted a library which would allow everything to be done in Python.\n",
    "    - Python is faster to develop in than Java, and is more general-purpose than R."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7a959a3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### `pandas` data structures\n",
    "\n",
    "There are three key data structures at the core of `pandas`:\n",
    "- DataFrame: 2 dimensional tables.\n",
    "- Series: 1 dimensional array-like object, typically representing a column or row.\n",
    "- Index: sequence of column or row labels.\n",
    "\n",
    "<center>\n",
    "    <img src='imgs/example-df.png' width=400>\n",
    "    <i>A DataFrame you'll see in Lab 1.</i>\n",
    "</center>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1129f156",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Importing `pandas` and related libraries\n",
    "\n",
    "`pandas` is almost always imported in conjunction with `numpy`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f14fcafa-a170-4c65-8921-9ccb867684a3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09f320d6",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Example: Dog Breeds (woof!) 🐶\n",
    "\n",
    "The dataset we'll work comes from the American Kennel Club. Here's a [cool plot](https://informationisbeautiful.net/visualizations/best-in-show-whats-the-top-data-dog/) made using our dataset.\n",
    "\n",
    "\n",
    "<center>\n",
    "    <img src=\"https://infobeautiful4.s3.amazonaws.com/2014/11/IIB_Best-In-Show_1276x2.png\" width=800>\n",
    "</center>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e5816af",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# You'll see the Path(...) / subpath syntax a lot.\n",
    "# It creates the correct path to your file, \n",
    "# whether you're using Windows, macOS, or Linux.\n",
    "dog_path = Path('data') / 'dogs43.csv'\n",
    "dogs = pd.read_csv(dog_path)\n",
    "dogs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37dfa85f-ec32-4e80-96c8-44a7e4648bb5",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Review: `head`, `tail`, `shape`, `index`, `get`, and `sort_values`\n",
    "\n",
    "To extract the first or last few rows of a DataFrame, use the `head` or `tail` methods."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40b81a37-c457-43ca-97ac-ba41e6192800",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.head(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d78c23d2-ea08-4c39-9bfb-534705770e92",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.tail(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7697d12-c931-4495-8c96-e4e0436ec6eb",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "The `shape` attribute returns the DataFrame's number of rows and columns."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5f544554-8a1c-4068-988c-fb8299820900",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b485d34-8303-4ba0-bbbf-98bc23d2b3d5",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# The default index of a DataFrame is 0, 1, 2, 3, ...\n",
    "dogs.index"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62715aaa-e801-4e15-b46a-8741df56351d",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "We know that we can use `.get()` to select out a column or multiple columns..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0e86468",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.get('breed')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e48a51ed-7ea4-4c3f-9355-4ffaf354df84",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.get(['breed', 'kind', 'longevity'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34c2821a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "Most people don't use `.get` in practice; we'll see the more common technique in a few slides."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2585a295",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "And lastly, remember that to sort by a column, use the `sort_values` method. Like most DataFrame and Series methods, `sort_values` returns a new DataFrame, and doesn't modify the original."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6495fe7e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Note that the index is no longer 0, 1, 2, ...!\n",
    "dogs.sort_values('height', ascending=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1dd6df12",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# This sorts by 'height', \n",
    "# then breaks ties by 'longevity'.\n",
    "# Note the difference in the last three rows between\n",
    "# this DataFrame and the one above.\n",
    "dogs.sort_values(['height', 'longevity'],\n",
    "                 ascending=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afa670fc",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "Note that `dogs` is not the DataFrame above. To save our changes, we'd need to say something like `dogs = dogs.sort_values...`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "052d364a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e14a96f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Setting the index\n",
    "\n",
    "Think of each row's index as its **unique identifier** or **name**. Often, we like to set the index of a DataFrame to a unique identifier if we have one available. We can do so with the `set_index` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5e1dcdda",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.set_index('breed')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e7f7a2e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# The above cell didn't involve an assignment statement,\n",
    "# so dogs was unchanged.\n",
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "febd1498",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# By reassigning dogs, our changes will persist.\n",
    "dogs = dogs.set_index('breed')\n",
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99147102",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# There used to be 7 columns, but now there are only 6!\n",
    "dogs.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dc48ad57-04c6-4b25-bf0c-16f9bbbbfb80",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "<div class=\"alert alert-warning\">\n",
    "    <h3>Question 🤔 (Answer at `lec02-index`)</h3>\n",
    "        \n",
    "<b>Ask <a href=\"https://chat.openai.com/\">ChatGPT</a>:</b>\n",
    "    \n",
    "- To explain what happens if you have duplicate values in a column and use `set_index()` on it.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "104c7638",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 💡 Pro-Tip: Displaying more rows/columns\n",
    "\n",
    "Sometimes, you just want `pandas` to display a lot of rows and columns. You can use this helper function to do that:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ea33e966",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from IPython.display import display\n",
    "def display_df(df, rows=pd.options.display.max_rows, cols=pd.options.display.max_columns):\n",
    "    \"\"\"Displays n rows and cols from df.\"\"\"\n",
    "    with pd.option_context(\"display.max_rows\", rows,\n",
    "                           \"display.max_columns\", cols):\n",
    "        display(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "020ff872",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "display_df(dogs.sort_values('weight', ascending=False),\n",
    "           rows=43)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58124491",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Selecting columns"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c142aa3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Selecting columns in `babypandas` 👶🐼\n",
    "\n",
    "- In `babypandas`, you selected columns using the `.get` method.\n",
    "- `.get` also works in `pandas`, but it is not **idiomatic** – people don't usually use it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b2c4566",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d7b67995",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.get('size')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9749741a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# This doesn't error, but sometimes we'd like it to.\n",
    "dogs.get('size oops!')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2db466c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Selecting columns with `[]`\n",
    "\n",
    "* The standard way to select a column in `pandas` is by using the `[]` operator.\n",
    "* Specifying a column name returns the column as a Series.\n",
    "* Specifying a list of column names returns a DataFrame."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5fe2c2a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afdc913a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Returns a Series.\n",
    "dogs['kind']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2cf38cf3",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Returns a DataFrame.\n",
    "dogs[['kind', 'size']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f33f6513",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 🤔\n",
    "dogs[['kind']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7d620b54",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": [
     "raises-exception"
    ]
   },
   "outputs": [],
   "source": [
    "# Breeds are stored in the index, which is not a column!\n",
    "# dogs['breed']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "74ce6f66",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.index"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77e32b3c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Useful Series methods\n",
    "\n",
    "There are a variety of useful methods that work on Series. You can see the entire list [here](https://pandas.pydata.org/docs/reference/api/pandas.Series.html). Many methods that work on a Series will also work on DataFrames, as we'll soon see."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "501cd9eb-37c2-4669-b7bc-ebb9c5b5cadc",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "014e7e53",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# What are the unique kinds of dogs?\n",
    "dogs['kind'].unique()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af60b15d",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# How many unique kinds of dogs are there?\n",
    "dogs['kind'].nunique()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "660aef64",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# What's the distribution of kinds?\n",
    "dogs['kind'].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d0da3249",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# What's the mean of the 'longevity' column?\n",
    "dogs['longevity'].mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93c6f30c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Tell me more about the 'weight' column.\n",
    "dogs['weight'].describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "be6b5ebc",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Sort the 'lifetime_cost' column. Note that here we're using sort_values on a Series, not a DataFrame!\n",
    "dogs['lifetime_cost'].sort_values()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "03e5ca18",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Gives us the index of the largest value, not the largest value itself.\n",
    "dogs['lifetime_cost'].idxmax()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7bd05aa",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Selecting subsets of rows (and columns)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35004e1e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Use `loc` to _slice_ rows and columns using labels\n",
    "\n",
    "You saw slicing in DSC 20.\n",
    "\n",
    "`loc` works similarly to slicing 2D arrays, but it uses row **labels** and column **labels**, not positions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c53204da",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bd7d016d",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# The first argument is the row label.\n",
    "#        ↓\n",
    "dogs.loc['Pug', 'longevity']\n",
    "#                  ↑\n",
    "# The second argument is the column label."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f54795e0",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "fragment"
    },
    "tags": []
   },
   "source": [
    "As an aside, `loc` is _not_ a method – it's an indexer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f74c2c85",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "type(dogs.loc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80c8461f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "type(dogs.sort_values)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "680f7e18-e49b-4763-a227-35503e029024",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### `.loc` is flexible 🧘\n",
    "\n",
    "You can provide a sequence (list, array, Series) as either argument to `.loc`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "661fa35d",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a1c9b6c0",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.loc[['Cocker Spaniel', 'Labrador Retriever'], 'size']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f88a77de-8073-4d46-8f0a-53fe0bdd6774",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.loc[['Cocker Spaniel', 'Labrador Retriever'], ['kind', 'size', 'height']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1fc39291",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "subslide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Note that the 'weight' column is included!\n",
    "dogs.loc[['Cocker Spaniel', 'Labrador Retriever'], 'lifetime_cost': 'weight']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "33b823df-bf41-42e7-b0e8-f9f98a0ff59b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.loc[['Cocker Spaniel', 'Labrador Retriever'], :]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a9bb163-6cf1-42a2-994f-71b5dbd8567f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Shortcut for the line above.\n",
    "dogs.loc[['Cocker Spaniel', 'Labrador Retriever']]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5adb344",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Review: Querying\n",
    "- As we saw in DSC 10, querying is the act of selecting rows in a DataFrame that satisfy certain condition(s).\n",
    "- Comparisons with arrays (or Series) result in Boolean arrays (or Series).\n",
    "- We can use comparisons along with the `loc` operator to **filter** a DataFrame."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe2f73f5",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7535d099",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.loc[dogs['weight'] < 10]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40805c1e-7e16-4196-92ac-be89ef31d878",
   "metadata": {
    "editable": true,
    "scrolled": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.loc[dogs.index.str.contains('Retriever')]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9318edf4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Because querying is so common, there's a shortcut:\n",
    "dogs[dogs.index.str.contains('Retriever')]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79ce6b2a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Empty DataFrame – not an error!\n",
    "dogs.loc[dogs['kind'] == 'beaver']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3161a69",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "Note that because we set the index to `'breed'` earlier, we can select rows based on dog breeds without having to query."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6ad44407",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "436fa37d",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Series!\n",
    "dogs.loc['Maltese']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46e8bf7a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "If `'breed'` was instead a column, then we'd need to query to access information about a particular breed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b461d5f8",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs_reset = dogs.reset_index()\n",
    "dogs_reset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2d0518f1",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# DataFrame!\n",
    "dogs_reset[dogs_reset['breed'] == 'Maltese']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "632b8d8f-c1a8-4b0a-b9f0-2404fc1ca7a4",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Querying with multiple conditions\n",
    "\n",
    "Remember, you need parentheses around each condition. Also, you must use the bitwise operators `&` and `|` instead of the standard `and` and `or` keywords. `pandas` makes weird decisions sometimes!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dce9f7db",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "32c7311f-5c9e-45a0-9600-619e944ca9fb",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs[(dogs['weight'] < 20) & (dogs['kind'] == 'terrier')]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c6feca9-68f0-41c6-8648-bedfe04599ca",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 💡 Pro-Tip: Using `.query`\n",
    "\n",
    "`.query` is a convenient way to query, since you don't need parentheses and you can use the `and` and `or` keywords."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d15b416a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56f7e9f3-f16f-41e4-9360-e69e48eaeb53",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.query('weight < 20 and kind == \"terrier\"')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72d9521a-a71c-4b54-900c-50169fb447de",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.query('kind in [\"sporting\", \"terrier\"] and lifetime_cost < 20000')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d18cfac-8767-45a9-8aed-565b32aec51b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "<div class=\"alert alert-warning\">\n",
    "    <h3>Question 🤔 (Answer at `lec02-query`)</h3>\n",
    "        \n",
    "<b>Ask <a href=\"https://chat.openai.com/\">ChatGPT</a>:</b>\n",
    "    \n",
    "- To explain when you would use `.query()` instead of `.loc[]` or the other way around.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e1a3a89",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Don't forget `iloc`!\n",
    "\n",
    "- `iloc` stands for \"integer location.\"\n",
    "- `iloc` is like `loc`, but it selects rows and columns based off of integer positions only, just like with 2D arrays."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2e3b6051",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd494f9f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.iloc[1:15, :-2]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "53425cfc",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "`iloc` is often most useful when we sort first. For instance, to find the weight of the longest-living dog breed in the dataset:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5c69f04-1e70-4f0c-a355-a4642019efe0",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.sort_values('longevity', ascending=False)['weight'].iloc[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1878d0e5",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Finding the breed itself involves sorting, but not iloc.\n",
    "dogs.sort_values('longevity', ascending=False).index[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0e0f6afd",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### More practice\n",
    "\n",
    "Consider the DataFrame below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84d1dd06",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "jack = pd.DataFrame({1: ['fee', 'fi'], \n",
    "                     '1': ['fo', 'fum']})\n",
    "jack"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "420f47d8",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "For each of the following pieces of code, predict what the output will be. Then, uncomment the line of code and see for yourself. We may not be able to cover these all in class; if so, make sure to try them on your own. [Here's a Pandas Tutor link](https://pandastutor.com/vis.html#code=import%20pandas%20as%20pd%0A%0Ajack%20%3D%20pd.DataFrame%28%7B1%3A%20%5B'fee',%20'fi'%5D,%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20'1'%3A%20%5B'fo',%20'fum'%5D%7D%29%0Ajack%5B1%5D&d=2023-10-05&lang=py&v=v1) to visualize these!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "660fa42d",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# jack[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac5ad541",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# jack[[1]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c1f7c00",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# jack['1']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24a90b6b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# jack[[1, 1]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bda6e0f9",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# jack.loc[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb96863b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# jack.loc[jack[1] == 'fo']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b83cc118",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# jack[1, ['1', 1]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4a157e2f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# jack.loc[1,1]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3a168d5",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "<div class=\"alert alert-warning\">\n",
    "    <h3>Questions? 🤔</h3>\n",
    "</div>\n",
    "    \n",
    "What questions do you have?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d58ea98",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "    <h3>We will probably have to end lecture here.</h3>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2eaeba51-a0c3-4ed7-b762-2d1bcae3162a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Adding and modifying columns"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48b0b604-3923-4d8d-a2ee-72c756f61fda",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Adding and modifying columns, using a copy\n",
    "\n",
    "- To add a new column to a DataFrame, use the `assign` method.\n",
    "    - To change the values in a column, add a new column with the same name as the existing column.\n",
    "- Like most `pandas` methods, `assign` returns a new DataFrame.\n",
    "    - **Pro** ✅: This doesn't inadvertently change any existing variables.\n",
    "    - **Con** ❌: It is not very space efficient, as it creates a new copy each time it is called."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c965145f-ae2a-4e19-a1c5-ca828c479883",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.assign(cost_per_year=dogs['lifetime_cost'] / dogs['longevity'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b6967445",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e4fc26b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 💡 Pro-Tip: Method chaining\n",
    "\n",
    "Chain methods together instead of writing long, hard-to-read lines."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e83ee9b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Finds the rows corresponding to the five cheapest to own breeds on a per-year basis.\n",
    "(dogs\n",
    " .assign(cost_per_year=dogs['lifetime_cost'] / dogs['longevity'])\n",
    " .sort_values('cost_per_year')\n",
    " .iloc[:5]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d26fe50",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 💡 Pro-Tip: `assign` for column names with special characters\n",
    "\n",
    "You can also use `assign` when the desired column name has spaces (and other special characters) by unpacking a dictionary:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b992959a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.assign(**{'cost per year 💵': dogs['lifetime_cost'] / dogs['longevity']})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cb6fa478",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Adding and modifying columns, in-place\n",
    "\n",
    "* You can assign a new column to a DataFrame **in-place** using `[]`.\n",
    "    - This works like dictionary assignment.\n",
    "    - This **modifies** the underlying DataFrame, unlike `assign`, which returns a new DataFrame.\n",
    "* This is the more \"common\" way of adding/modifying columns. \n",
    "    - ⚠️ Warning: Exercise caution when using this approach, since this approach changes the values of existing variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f598df4c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# By default, .copy() returns a deep copy of the object it is called on,\n",
    "# meaning that if you change the copy the original remains unmodified.\n",
    "dogs_copy = dogs.copy()\n",
    "dogs_copy.head(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba1f0726",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs_copy['cost_per_year'] = dogs_copy['lifetime_cost'] / dogs_copy['longevity']\n",
    "dogs_copy"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b5d2ac1",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "fragment"
    },
    "tags": []
   },
   "source": [
    "Note that we never reassigned `dogs_copy` in the cell above – that is, we never wrote `dogs_copy = ...` – though it was still modified."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76a86690",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Mutability\n",
    "\n",
    "DataFrames, like lists, arrays, and dictionaries, are **mutable**. As you learned in DSC 20, this means that they can be modified after being created. (For instance, the list `.append` method mutates in-place.)\n",
    "\n",
    "Not only does this explain the behavior on the previous slide, but it also explains the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "574b4b11",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs_copy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe506f4a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def cost_in_thousands():\n",
    "    dogs_copy['lifetime_cost'] = dogs_copy['lifetime_cost'] / 1000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb1be3f8",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# What happens when we run this twice?\n",
    "cost_in_thousands()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b3b53db2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs_copy"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6cbd332",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### ⚠️ Avoid mutation when possible\n",
    "\n",
    "Note that `dogs_copy` was modified, even though we didn't reassign it! These unintended consequences can **influence the behavior of test cases on labs and projects**, among other things! \n",
    "\n",
    "To avoid this, it's a good idea to avoid mutation when possible. If you must use mutation, include `df = df.copy()` as the first line in functions that take DataFrames as input.\n",
    "\n",
    "Also, some methods let you use the `inplace=True` argument to mutate the original. **Don't use this argument, since future `pandas` releases plan to remove it.**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5549d72e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## `pandas` and `numpy`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "099f532e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "<center><img src='imgs/python-stack.png' width=60%></center>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d5900bf",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### `pandas` is built upon `numpy`!\n",
    "\n",
    "- A Series in `pandas` is a `numpy` array with an index.\n",
    "- A DataFrame is like a dictionary of columns, each of which is a `numpy` array.\n",
    "- Many operations in `pandas` are fast because they use `numpy`'s implementations, which are written in fast languages like C.\n",
    "- If you need access the array underlying a DataFrame or Series, use the `to_numpy` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "da955778",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs['lifetime_cost']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91195593",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs['lifetime_cost'].to_numpy()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e1c6a1f",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### `pandas` data types\n",
    "\n",
    "- Each Series (column) has a `numpy` data type, which refers to the type of the values stored within. Access it using the `dtypes` attribute.\n",
    "- A column's data type determines which operations can be applied to it.\n",
    "- `pandas` tries to guess the correct data types for a given DataFrame, and is often wrong.\n",
    "    - This can lead to incorrect calculations and poor memory/time performance.\n",
    "- As a result, you will often need to explicitly convert between data types."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6372e856",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd039187",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.dtypes"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2484929",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### `pandas` data types\n",
    "\n",
    "Notice that Python `str` types are `object` types in `numpy` and `pandas`.\n",
    "\n",
    "|Pandas dtype|Python type|NumPy type|SQL type|Usage|\n",
    "|---|---|---|---|---|\n",
    "|int64|int|int_, int8,...,int64, uint8,...,uint64|INT, BIGINT| Integer numbers|\n",
    "|float64|float|float_, float16, float32, float64|FLOAT| Floating point numbers|\n",
    "|bool|bool|bool_|BOOL|True/False values|\n",
    "|datetime64 or Timestamp|datetime.datetime|datetime64|DATETIME|Date and time values|\n",
    "|timedelta64 or Timedelta|datetime.timedelta|timedelta64|NA|Differences between two datetimes|\n",
    "|category|NA|NA|ENUM|Finite list of text values|\n",
    "|object|str|string, unicode|NA|Text|\n",
    "|object|NA|object|NA|Mixed types|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93ca8db1",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "[This article](https://www.dataquest.io/blog/pandas-big-data/) details how `pandas` stores different data types under the hood.\n",
    "\n",
    "[This article](https://mortada.net/can-integer-operations-overflow-in-python.html#Can-integers-overflow-in-python?) explains how `numpy`/`pandas` `int64` operations differ from vanilla `int` operations."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fea361cc",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Type conversion\n",
    "\n",
    "You can change the data type of a Series using the `.astype` Series method.\n",
    "\n",
    "For example, we can change the data type of the `'lifetime_cost'` column in `dogs` to be `uint32`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4309975a",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "22c66798",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Gives the types as well as the space taken up by the DataFrame.\n",
    "dogs.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb1ce8c9",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs['lifetime_cost'] = dogs['lifetime_cost'].astype('uint32')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "87405f1b",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "source": [
    "Now, the DataFrame takes up less space! This may be insignificant in our DataFrame, but makes a difference when working with larger datasets."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1581d5ea",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.info()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0c9de4e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 💡 Pro-Tip: Setting `dtype`s in `read_csv`\n",
    "\n",
    "Usually, we prefer to set the correct dtypes in `read_csv`, since it can help `pandas` load in files more quickly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "65faf7f6",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dog_path"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "986d34c2",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs = pd.read_csv(dog_path, dtype={'lifetime_cost': 'uint32'})\n",
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d8ae92f0",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs.dtypes"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fffa5177",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Axes\n",
    "\n",
    "- The rows and columns of a DataFrame are both stored as Series.\n",
    "- The **axis** specifies the direction of a **slice** of a DataFrame.\n",
    "\n",
    "<center><img src='imgs/axis.png' width=30%></center>\n",
    "\n",
    "- Axis 0 refers to the index (rows).\n",
    "- Axis 1 refers to the columns.\n",
    "- **These are the same axes definitions that 2D `numpy` arrays have!**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e91a09c",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### DataFrame methods with `axis`\n",
    "\n",
    "- Many Series methods work on DataFrames.\n",
    "- In such cases, the DataFrame method usually applies the Series method to every row or column.\n",
    "- Many of these methods accept an `axis` argument; the default is usually `axis=0`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e674deb",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "89854475",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Max element in each column.\n",
    "dogs.max()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "01f5af45",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Max element in each row – throws an error since there are different types in each row.\n",
    "# dogs.max(axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9a6231eb",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# The number of unique values in each column.\n",
    "dogs.nunique()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "942d387e",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# describe doesn't accept an axis argument; it works on every numeric column in the DataFrame it is called on.\n",
    "dogs.describe()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d52afb2d",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<h3>Exercise</h3>\n",
    "Pick a dog breed that you personally like or know the name of. Then:\n",
    "<ul>\n",
    "    <li>Try to find a few other dog breeds that are similar in weight to yours in <code>all_dogs</code>.</li>\n",
    "    <li>Which similar breeds have the lowest and highest <code>'lifetime_cost'</code>? <code>'intelligence_rank'</code>?</li>\n",
    "    <li>Are there any similar breeds that you haven't heard of before?</li>\n",
    "</ul>\n",
    "<br>\n",
    "    For fun, look up these dog breeds on the <a href=\"https://www.akc.org/\">AKC website</a> to see what they look like!\n",
    "</div>\n",
    "\n",
    "<!-- As a bonus, look up these dog breeds on the [AKC website](https://www.akc.org/) to see how they look! -->"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13b5f3e7",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "all_dogs = pd.read_csv(Path('data') / 'all_dogs.csv')\n",
    "all_dogs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a1296237",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": ""
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Your code goes here."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "78158504",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## Summary, next time"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b89b6ab7",
   "metadata": {
    "editable": true,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### Summary\n",
    "\n",
    "- `pandas` is **the** library for tabular data manipulation in Python.\n",
    "- There are three key data structures in `pandas`: DataFrame, Series, and Index.\n",
    "- Refer to the lecture notebook and the [`pandas` documentation](https://pandas.pydata.org/docs/user_guide/index.html#user-guide) for tips.\n",
    "- `pandas` relies heavily on `numpy`. An understanding of how data types work in both will allow you to write more efficient and bug-free code.\n",
    "- Series and DataFrames share many methods (refer to the [`pandas` documentation](https://pandas.pydata.org/docs/user_guide/index.html#user-guide) for more details).\n",
    "- Most `pandas` methods return copies of Series/DataFrames. Be careful when using techniques that modify values in-place.\n",
    "- Next time: `groupby` and data granularity."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.1"
  },
  "livereveal": {
   "scroll": true
  },
  "rise": {
   "transition": "none"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
