{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# Introduction to Pandas\n",
    "\n",
    "Pandas is a library providing high-performance, easy-to-use data structures and data analysis tools. The core of pandas is its *dataframe* which is essentially a table of data. Pandas provides easy and powerful ways to import data from a variety of sources and export it to just as many. It is also explicitly designed to handle *missing data* elegantly which is a very common problem in data from the real world.\n",
    "\n",
    "The offical [pandas documentation](http://pandas.pydata.org/pandas-docs/stable/) is very comprehensive and you will be answer a lot of questions in there, however, it can sometimes be hard to find the right page. Don't be afraid to use Google to find help."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pandas has a standard convention for importing it which you will see used in a lot of documentation so we will follow that in this course:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from pandas import Series, DataFrame"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Series\n",
    "\n",
    "The simplest of pandas' data structures is the `Series`. It is a one-dimensional list-like structure.\n",
    "Let's create one from a `list`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    14\n",
       "1     7\n",
       "2     3\n",
       "3    -7\n",
       "4     8\n",
       "dtype: int64"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Series([14, 7, 3, -7, 8])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are three main components to this output.\n",
    "The first column (`0`, `2`, etc.) is the index, by default this is numbers each row starting from zero.\n",
    "The second column is our data, stored i the same order we entered it in our list.\n",
    "Finally at the bottom there is the `dtype` which stands for 'data type' which is telling us that all our data is being stored as a 64-bit integer.\n",
    "Usually you can ignore the `dtype` until you start doing more advanced things.\n",
    "\n",
    "In the first example above we allowed pandas to automatically create an index for our `Series` (this is the `0`, `1`, `2`, etc. in the left column) but often you will want to specify one yourself"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    14\n",
      "b     7\n",
      "c     3\n",
      "d    -7\n",
      "e     8\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "s = Series([14, 7, 3, -7, 8], index=['a', 'b', 'c', 'd', 'e'])\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can use this index to retrieve individual rows"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s['a']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "to replace values in the series"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "s['c'] = -1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "or to get a set of rows"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "a    14\n",
       "c    -1\n",
       "d    -7\n",
       "dtype: int64"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[['a', 'c', 'd']]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise 1\n",
    "\n",
    "- Create a Pandas `Series` with 10 or so elements where the indices are years and the values are numbers.\n",
    "- Experiment with retrieving elements from the `Series`.\n",
    "- Try making another `Series` with duplicate values in the index, what happens when you access those elements?\n",
    "- How does a Pandas `Series` differ from a Python `list` or `dict`?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2000    4.0\n",
       "2001    7.1\n",
       "2002    7.3\n",
       "2003    7.8\n",
       "2004    8.1\n",
       "dtype: float64"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "ex1_1 = Series([4, 7.1, 7.3, 7.8, 8.1], index=[2000, 2001, 2002, 2003, 2004])\n",
    "\n",
    "ex1_1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7.2999999999999998"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "ex1_1[2002]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2001    7.1\n",
       "2004    8.1\n",
       "dtype: float64"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "ex1_1[[2001, 2004]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2000    4.0\n",
       "2001    7.1\n",
       "2004    7.3\n",
       "2001    7.8\n",
       "2004    8.1\n",
       "dtype: float64"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "ex1_2 = Series([4, 7.1, 7.3, 7.8, 8.1], index=[2000, 2001, 2004, 2001, 2004])\n",
    "\n",
    "ex1_2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2001    7.1\n",
       "2001    7.8\n",
       "dtype: float64"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "ex1_2[2001]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Series operations\n",
    "\n",
    "A `Series` is `list`-like in the sense that it is an ordered set of values. It is also `dict`-like since its entries can be accessed via key lookup. One very important way in which is differs is how it allows operations to be done over the whole `Series` in one go, a technique often referred to as 'broadcasting'.\n",
    "\n",
    "A simple example is wanting to double the value of every entry in a set of data. In standard Python, you might have a list like"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "my_list = [3, 6, 8, 4, 10]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you wanted to double every entry you might try simply multiplying the list by `2`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 6, 8, 4, 10, 3, 6, 8, 4, 10]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_list * 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "but as you can see, that simply duplicated the elements. Instead you would have to use a `for` loop or a list comprehension:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[6, 12, 16, 8, 20]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[i * 2 for i in my_list]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With a pandas `Series`, however, you can perform bulk mathematical operations to the whole series in one go:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0     3\n",
      "1     6\n",
      "2     8\n",
      "3     4\n",
      "4    10\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "my_series = Series(my_list)\n",
    "print(my_series)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0     6\n",
       "1    12\n",
       "2    16\n",
       "3     8\n",
       "4    20\n",
       "dtype: int64"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "my_series * 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As well as bulk modifications, you can perform bulk selections by putting more complex statements in the square brackets:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "c   -1\n",
       "d   -7\n",
       "dtype: int64"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[s < 0]  # All negative entries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "a    14\n",
       "b     7\n",
       "e     8\n",
       "dtype: int64"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[(s * 2) > 4]  # All entries which, when doubled are greater than 4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These operations work because the `Series` index selection can be passed a series of `True` and `False` values which it then uses to filter the result:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "a     True\n",
       "b     True\n",
       "c    False\n",
       "d    False\n",
       "e     True\n",
       "dtype: bool"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(s * 2) > 4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here you can see that the rows `a`, `b` and `e` are `True` while the others are `False`. Passing this to `s[...]` will only show rows that are `True`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Multi-Series operations\n",
    "\n",
    "It is also possible to perform operations between two `Series` objects:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    16\n",
       "1    -1\n",
       "2    29\n",
       "3     3\n",
       "4     2\n",
       "dtype: int64"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s2 = Series([23,5,34,7,5])\n",
    "s3 = Series([7, 6, 5,4,3])\n",
    "s2 - s3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise 2\n",
    "\n",
    "- Create two `Series` objects of equal length with no specified index and containing any values you like. Perform some mathematical operations on them and experiment to make sure it works how you think.\n",
    "- What happens then you perform an operation on two series which have different lengths? How does this change when you give the series some indices?\n",
    "- Using the `Series` from the first exercise with the years for the index, Select all entries with even-numbered years. Also, select all those with odd-numbered years."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0     4\n",
       "1    10\n",
       "2    14\n",
       "3    11\n",
       "4     6\n",
       "5     7\n",
       "dtype: int64"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "ex2_1a = Series([1,3,5,7,4,3])\n",
    "ex2_1b = Series([3,7,9,4,2,4])\n",
    "\n",
    "ex2_1a + ex2_1b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0     4.0\n",
       "1    10.0\n",
       "2    14.0\n",
       "3    11.0\n",
       "4     NaN\n",
       "5     NaN\n",
       "dtype: float64"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "ex2_2a = Series([1,3,5,7,4,3])\n",
    "ex2_2b = Series([3,7,9,4])\n",
    "\n",
    "ex2_2a + ex2_2b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1     4.0\n",
       "2     NaN\n",
       "3    12.0\n",
       "4     NaN\n",
       "5    13.0\n",
       "6     NaN\n",
       "7     NaN\n",
       "dtype: float64"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "ex2_2a = Series([1,3,5,7,4,3], index=[1,2,3,4,5,6])\n",
    "ex2_2b = Series([3,7,9,4], index=[1,3,5,7])\n",
    "\n",
    "ex2_2a + ex2_2b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2000    4.0\n",
       "2002    7.3\n",
       "2004    8.1\n",
       "dtype: float64"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ex1_1[ex1_1.index % 2 == 0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## DataFrame\n",
    "\n",
    "While you can think of the `Series` as a one-dimensional list of data, pandas' `DataFrame` is a two (or possibly more) dimensional table of data. You can think of each column in the table as being a `Series`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = {'city': ['Paris', 'Paris', 'Paris', 'Paris',\n",
    "                 'London', 'London', 'London', 'London',\n",
    "                 'Rome', 'Rome', 'Rome', 'Rome'],\n",
    "        'year': [2001, 2008, 2009, 2010,\n",
    "                 2001, 2006, 2011, 2015,\n",
    "                 2001, 2006, 2009, 2012],\n",
    "        'pop': [2.148, 2.211, 2.234, 2.244,\n",
    "                7.322, 7.657, 8.174, 8.615,\n",
    "                2.547, 2.627, 2.734, 2.627]}\n",
    "df = DataFrame(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This has created a `DataFrame` from the dictionary `data`. The keys will become the column headers and the values will be the values in each column. As with the `Series`, an index will be created automatically."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>city</th>\n",
       "      <th>pop</th>\n",
       "      <th>year</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.148</td>\n",
       "      <td>2001</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.211</td>\n",
       "      <td>2008</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.234</td>\n",
       "      <td>2009</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.244</td>\n",
       "      <td>2010</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>London</td>\n",
       "      <td>7.322</td>\n",
       "      <td>2001</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>London</td>\n",
       "      <td>7.657</td>\n",
       "      <td>2006</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>London</td>\n",
       "      <td>8.174</td>\n",
       "      <td>2011</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>London</td>\n",
       "      <td>8.615</td>\n",
       "      <td>2015</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>Rome</td>\n",
       "      <td>2.547</td>\n",
       "      <td>2001</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>Rome</td>\n",
       "      <td>2.627</td>\n",
       "      <td>2006</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>Rome</td>\n",
       "      <td>2.734</td>\n",
       "      <td>2009</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>Rome</td>\n",
       "      <td>2.627</td>\n",
       "      <td>2012</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      city    pop  year\n",
       "0    Paris  2.148  2001\n",
       "1    Paris  2.211  2008\n",
       "2    Paris  2.234  2009\n",
       "3    Paris  2.244  2010\n",
       "4   London  7.322  2001\n",
       "5   London  7.657  2006\n",
       "6   London  8.174  2011\n",
       "7   London  8.615  2015\n",
       "8     Rome  2.547  2001\n",
       "9     Rome  2.627  2006\n",
       "10    Rome  2.734  2009\n",
       "11    Rome  2.627  2012"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Or, if you just want a peek at the data, you can just grab the first few rows with:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>city</th>\n",
       "      <th>pop</th>\n",
       "      <th>year</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.148</td>\n",
       "      <td>2001</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.211</td>\n",
       "      <td>2008</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.234</td>\n",
       "      <td>2009</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    city    pop  year\n",
       "0  Paris  2.148  2001\n",
       "1  Paris  2.211  2008\n",
       "2  Paris  2.234  2009"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.head(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since we passed in a dictionary to the `DataFrame` constructor, the order of the columns will not necessarilly match the order in which you defined them. To enforce a certain order, you can pass a `columns` argument to the constructor giving a list of the columns in the order you want them:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>year</th>\n",
       "      <th>city</th>\n",
       "      <th>pop</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2001</td>\n",
       "      <td>Paris</td>\n",
       "      <td>2.148</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2008</td>\n",
       "      <td>Paris</td>\n",
       "      <td>2.211</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2009</td>\n",
       "      <td>Paris</td>\n",
       "      <td>2.234</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2010</td>\n",
       "      <td>Paris</td>\n",
       "      <td>2.244</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2001</td>\n",
       "      <td>London</td>\n",
       "      <td>7.322</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>2006</td>\n",
       "      <td>London</td>\n",
       "      <td>7.657</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2011</td>\n",
       "      <td>London</td>\n",
       "      <td>8.174</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>2015</td>\n",
       "      <td>London</td>\n",
       "      <td>8.615</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>2001</td>\n",
       "      <td>Rome</td>\n",
       "      <td>2.547</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>2006</td>\n",
       "      <td>Rome</td>\n",
       "      <td>2.627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>2009</td>\n",
       "      <td>Rome</td>\n",
       "      <td>2.734</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>2012</td>\n",
       "      <td>Rome</td>\n",
       "      <td>2.627</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    year    city    pop\n",
       "0   2001   Paris  2.148\n",
       "1   2008   Paris  2.211\n",
       "2   2009   Paris  2.234\n",
       "3   2010   Paris  2.244\n",
       "4   2001  London  7.322\n",
       "5   2006  London  7.657\n",
       "6   2011  London  8.174\n",
       "7   2015  London  8.615\n",
       "8   2001    Rome  2.547\n",
       "9   2006    Rome  2.627\n",
       "10  2009    Rome  2.734\n",
       "11  2012    Rome  2.627"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "DataFrame(data, columns=['year', 'city', 'pop'])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When we accessed elements from a `Series` object, it would select an element by row. However, by default `DataFrame`s index primarily by column. You can access any column directly by using square brackets or by named attributes:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0     2001\n",
       "1     2008\n",
       "2     2009\n",
       "3     2010\n",
       "4     2001\n",
       "5     2006\n",
       "6     2011\n",
       "7     2015\n",
       "8     2001\n",
       "9     2006\n",
       "10    2009\n",
       "11    2012\n",
       "Name: year, dtype: int64"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['year']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0      Paris\n",
       "1      Paris\n",
       "2      Paris\n",
       "3      Paris\n",
       "4     London\n",
       "5     London\n",
       "6     London\n",
       "7     London\n",
       "8       Rome\n",
       "9       Rome\n",
       "10      Rome\n",
       "11      Rome\n",
       "Name: city, dtype: object"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.city"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Accessing a column like this returns a `Series` which will act in the same way as those we were using earlier.\n",
    "\n",
    "Note that there is one additional part to this output, `Name: city`. Pandas has remembered that this `Series` was created from the `'city'` column in the `DataFrame`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "pandas.core.series.Series"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(df.city)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0      True\n",
       "1      True\n",
       "2      True\n",
       "3      True\n",
       "4     False\n",
       "5     False\n",
       "6     False\n",
       "7     False\n",
       "8     False\n",
       "9     False\n",
       "10    False\n",
       "11    False\n",
       "Name: city, dtype: bool"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.city == 'Paris'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This has created a new `Series` which has `True` set where the city is Paris and `False` elsewhere.\n",
    "\n",
    "We can use filtered `Series` like this to filter the `DataFrame` as a whole. `df.city == 'Paris'` has returned a `Series` containing booleans. Passing it back into `df` as an indexing operation will use it to filter based on the `'city'` column."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>city</th>\n",
       "      <th>pop</th>\n",
       "      <th>year</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.148</td>\n",
       "      <td>2001</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.211</td>\n",
       "      <td>2008</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.234</td>\n",
       "      <td>2009</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.244</td>\n",
       "      <td>2010</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    city    pop  year\n",
       "0  Paris  2.148  2001\n",
       "1  Paris  2.211  2008\n",
       "2  Paris  2.234  2009\n",
       "3  Paris  2.244  2010"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[df.city == 'Paris']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can then carry on and grab another column after that filter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    2001\n",
       "1    2008\n",
       "2    2009\n",
       "3    2010\n",
       "Name: year, dtype: int64"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[df.city == 'Paris'].year"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you want to select a **row** from a `DataFrame` then you can use the `.loc` attribute which allows you to pass index values like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "city    Paris\n",
       "pop     2.234\n",
       "year     2009\n",
       "Name: 2, dtype: object"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.loc[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Paris'"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df.loc[2]['city']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Adding new columns\n",
    "\n",
    "New columns can be added to a `DataFrame` simply by assigning them by index (as you would for a Python `dict`) and can be deleted with the `del` keyword in the same way:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>city</th>\n",
       "      <th>pop</th>\n",
       "      <th>year</th>\n",
       "      <th>continental</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.148</td>\n",
       "      <td>2001</td>\n",
       "      <td>True</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.211</td>\n",
       "      <td>2008</td>\n",
       "      <td>True</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.234</td>\n",
       "      <td>2009</td>\n",
       "      <td>True</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>Paris</td>\n",
       "      <td>2.244</td>\n",
       "      <td>2010</td>\n",
       "      <td>True</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>London</td>\n",
       "      <td>7.322</td>\n",
       "      <td>2001</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>London</td>\n",
       "      <td>7.657</td>\n",
       "      <td>2006</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>London</td>\n",
       "      <td>8.174</td>\n",
       "      <td>2011</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>London</td>\n",
       "      <td>8.615</td>\n",
       "      <td>2015</td>\n",
       "      <td>False</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>Rome</td>\n",
       "      <td>2.547</td>\n",
       "      <td>2001</td>\n",
       "      <td>True</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>Rome</td>\n",
       "      <td>2.627</td>\n",
       "      <td>2006</td>\n",
       "      <td>True</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>Rome</td>\n",
       "      <td>2.734</td>\n",
       "      <td>2009</td>\n",
       "      <td>True</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>Rome</td>\n",
       "      <td>2.627</td>\n",
       "      <td>2012</td>\n",
       "      <td>True</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      city    pop  year  continental\n",
       "0    Paris  2.148  2001         True\n",
       "1    Paris  2.211  2008         True\n",
       "2    Paris  2.234  2009         True\n",
       "3    Paris  2.244  2010         True\n",
       "4   London  7.322  2001        False\n",
       "5   London  7.657  2006        False\n",
       "6   London  8.174  2011        False\n",
       "7   London  8.615  2015        False\n",
       "8     Rome  2.547  2001         True\n",
       "9     Rome  2.627  2006         True\n",
       "10    Rome  2.734  2009         True\n",
       "11    Rome  2.627  2012         True"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df['continental'] = df.city != 'London'\n",
    "df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "del df['continental']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise 3\n",
    "\n",
    "- Create the `DataFrame` containing the census data for the three cities.\n",
    "- Select the data for the year 2001. Which city had the smallest population that year?\n",
    "- Find all the cities which had a population smaller than 2.6 million."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     city    pop  year\n",
      "0   Paris  2.148  2001\n",
      "4  London  7.322  2001\n",
      "8    Rome  2.547  2001\n"
     ]
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "print(df[df.year == 2001])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    city    pop  year\n",
      "0  Paris  2.148  2001\n",
      "1  Paris  2.211  2008\n",
      "2  Paris  2.234  2009\n",
      "3  Paris  2.244  2010\n",
      "8   Rome  2.547  2001\n"
     ]
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "print(df[df['pop'] < 2.6])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reading from file\n",
    "\n",
    "One of the msot common situations is that you have some data file containing the data you want to read. Perhaps this is data you've produced yourself or maybe it's from a collegue. In an ideal world the file will be perfectly formatted and will be trivial to import into pandas but since this is so often not the case, it provides a number of features to make your ife easier.\n",
    "\n",
    "Full information on reading and writing is available in the pandas manual on [IO tools](http://pandas.pydata.org/pandas-docs/stable/io.html) but first it's worth noting the common formats that pandas can work with:\n",
    "- Comma separated tables (or tab-separated or space-separated etc.)\n",
    "- Excel spreadsheets\n",
    "- HDF5 files\n",
    "- SQL databases\n",
    "\n",
    "For this course we will focus on plain-text CSV files as they are perhaps the most common format. Imagine we have a CSV file like (you can download this file from [city_pop.csv](https://raw.githubusercontent.com/milliams/data_analysis_python/master/city_pop.csv)):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is an example CSV file\r\n",
      "The text at the top here is not part of the data but instead is here\r\n",
      "to describe the file. You'll see this quite often in real-world data.\r\n",
      "A -1 signifies a missing value.\r\n",
      "\r\n",
      "year;London;Paris;Rome\r\n",
      "2001;7.322;2.148;2.547\r\n",
      "2006;7.652;;2.627\r\n",
      "2008;-1;2.211;\r\n",
      "2009;-1;2.234;2.734\r\n",
      "2011;8.174;;\r\n",
      "2012;-1;2.244;2.627\r\n",
      "2015;8.615;;\r\n"
     ]
    }
   ],
   "source": [
    "!cat city_pop.csv  # Uses the IPython 'magic' !cat to print the file"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can use the pandas function `read_csv()` to read the file and convert it to a `DataFrame`. Full documentation for this function can be found in [the manual](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html) or, as with any Python object, directly in the notebook by putting a `?` after the name:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function read_csv in module pandas.io.parsers:\n",
      "\n",
      "read_csv(filepath_or_buffer, sep=',', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression='infer', thousands=None, decimal=b'.', lineterminator=None, quotechar='\"', quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=False, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, skip_footer=0, doublequote=True, delim_whitespace=False, as_recarray=False, compact_ints=False, use_unsigned=False, low_memory=True, buffer_lines=None, memory_map=False, float_precision=None)\n",
      "    Read CSV (comma-separated) file into DataFrame\n",
      "    \n",
      "    Also supports optionally iterating or breaking of the file\n",
      "    into chunks.\n",
      "    \n",
      "    Additional help can be found in the `online docs for IO Tools\n",
      "    <http://pandas.pydata.org/pandas-docs/stable/io.html>`_.\n",
      "    \n",
      "    Parameters\n",
      "    ----------\n",
      "    filepath_or_buffer : str, pathlib.Path, py._path.local.LocalPath or any object with a read() method (such as a file handle or StringIO)\n",
      "        The string could be a URL. Valid URL schemes include http, ftp, s3, and\n",
      "        file. For file URLs, a host is expected. For instance, a local file could\n",
      "        be file ://localhost/path/to/table.csv\n",
      "    sep : str, default ','\n",
      "        Delimiter to use. If sep is None, the C engine cannot automatically detect\n",
      "        the separator, but the Python parsing engine can, meaning the latter will\n",
      "        be used automatically. In addition, separators longer than 1 character and\n",
      "        different from ``'\\s+'`` will be interpreted as regular expressions and\n",
      "        will also force the use of the Python parsing engine. Note that regex\n",
      "        delimiters are prone to ignoring quoted data. Regex example: ``'\\r\\t'``\n",
      "    delimiter : str, default ``None``\n",
      "        Alternative argument name for sep.\n",
      "    delim_whitespace : boolean, default False\n",
      "        Specifies whether or not whitespace (e.g. ``' '`` or ``'    '``) will be\n",
      "        used as the sep. Equivalent to setting ``sep='\\s+'``. If this option\n",
      "        is set to True, nothing should be passed in for the ``delimiter``\n",
      "        parameter.\n",
      "    \n",
      "        .. versionadded:: 0.18.1 support for the Python parser.\n",
      "    \n",
      "    header : int or list of ints, default 'infer'\n",
      "        Row number(s) to use as the column names, and the start of the data.\n",
      "        Default behavior is as if set to 0 if no ``names`` passed, otherwise\n",
      "        ``None``. Explicitly pass ``header=0`` to be able to replace existing\n",
      "        names. The header can be a list of integers that specify row locations for\n",
      "        a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not\n",
      "        specified will be skipped (e.g. 2 in this example is skipped). Note that\n",
      "        this parameter ignores commented lines and empty lines if\n",
      "        ``skip_blank_lines=True``, so header=0 denotes the first line of data\n",
      "        rather than the first line of the file.\n",
      "    names : array-like, default None\n",
      "        List of column names to use. If file contains no header row, then you\n",
      "        should explicitly pass header=None. Duplicates in this list are not\n",
      "        allowed unless mangle_dupe_cols=True, which is the default.\n",
      "    index_col : int or sequence or False, default None\n",
      "        Column to use as the row labels of the DataFrame. If a sequence is given, a\n",
      "        MultiIndex is used. If you have a malformed file with delimiters at the end\n",
      "        of each line, you might consider index_col=False to force pandas to _not_\n",
      "        use the first column as the index (row names)\n",
      "    usecols : array-like or callable, default None\n",
      "        Return a subset of the columns. If array-like, all elements must either\n",
      "        be positional (i.e. integer indices into the document columns) or strings\n",
      "        that correspond to column names provided either by the user in `names` or\n",
      "        inferred from the document header row(s). For example, a valid array-like\n",
      "        `usecols` parameter would be [0, 1, 2] or ['foo', 'bar', 'baz'].\n",
      "    \n",
      "        If callable, the callable function will be evaluated against the column\n",
      "        names, returning names where the callable function evaluates to True. An\n",
      "        example of a valid callable argument would be ``lambda x: x.upper() in\n",
      "        ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster\n",
      "        parsing time and lower memory usage.\n",
      "    as_recarray : boolean, default False\n",
      "        DEPRECATED: this argument will be removed in a future version. Please call\n",
      "        `pd.read_csv(...).to_records()` instead.\n",
      "    \n",
      "        Return a NumPy recarray instead of a DataFrame after parsing the data.\n",
      "        If set to True, this option takes precedence over the `squeeze` parameter.\n",
      "        In addition, as row indices are not available in such a format, the\n",
      "        `index_col` parameter will be ignored.\n",
      "    squeeze : boolean, default False\n",
      "        If the parsed data only contains one column then return a Series\n",
      "    prefix : str, default None\n",
      "        Prefix to add to column numbers when no header, e.g. 'X' for X0, X1, ...\n",
      "    mangle_dupe_cols : boolean, default True\n",
      "        Duplicate columns will be specified as 'X.0'...'X.N', rather than\n",
      "        'X'...'X'. Passing in False will cause data to be overwritten if there\n",
      "        are duplicate names in the columns.\n",
      "    dtype : Type name or dict of column -> type, default None\n",
      "        Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32}\n",
      "        Use `str` or `object` to preserve and not interpret dtype.\n",
      "        If converters are specified, they will be applied INSTEAD\n",
      "        of dtype conversion.\n",
      "    engine : {'c', 'python'}, optional\n",
      "        Parser engine to use. The C engine is faster while the python engine is\n",
      "        currently more feature-complete.\n",
      "    converters : dict, default None\n",
      "        Dict of functions for converting values in certain columns. Keys can either\n",
      "        be integers or column labels\n",
      "    true_values : list, default None\n",
      "        Values to consider as True\n",
      "    false_values : list, default None\n",
      "        Values to consider as False\n",
      "    skipinitialspace : boolean, default False\n",
      "        Skip spaces after delimiter.\n",
      "    skiprows : list-like or integer or callable, default None\n",
      "        Line numbers to skip (0-indexed) or number of lines to skip (int)\n",
      "        at the start of the file.\n",
      "    \n",
      "        If callable, the callable function will be evaluated against the row\n",
      "        indices, returning True if the row should be skipped and False otherwise.\n",
      "        An example of a valid callable argument would be ``lambda x: x in [0, 2]``.\n",
      "    skipfooter : int, default 0\n",
      "        Number of lines at bottom of file to skip (Unsupported with engine='c')\n",
      "    skip_footer : int, default 0\n",
      "        DEPRECATED: use the `skipfooter` parameter instead, as they are identical\n",
      "    nrows : int, default None\n",
      "        Number of rows of file to read. Useful for reading pieces of large files\n",
      "    na_values : scalar, str, list-like, or dict, default None\n",
      "        Additional strings to recognize as NA/NaN. If dict passed, specific\n",
      "        per-column NA values.  By default the following values are interpreted as\n",
      "        NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan',\n",
      "        '1.#IND', '1.#QNAN', 'N/A', 'NA', 'NULL', 'NaN', 'nan'`.\n",
      "    keep_default_na : bool, default True\n",
      "        If na_values are specified and keep_default_na is False the default NaN\n",
      "        values are overridden, otherwise they're appended to.\n",
      "    na_filter : boolean, default True\n",
      "        Detect missing value markers (empty strings and the value of na_values). In\n",
      "        data without any NAs, passing na_filter=False can improve the performance\n",
      "        of reading a large file\n",
      "    verbose : boolean, default False\n",
      "        Indicate number of NA values placed in non-numeric columns\n",
      "    skip_blank_lines : boolean, default True\n",
      "        If True, skip over blank lines rather than interpreting as NaN values\n",
      "    parse_dates : boolean or list of ints or names or list of lists or dict, default False\n",
      "    \n",
      "        * boolean. If True -> try parsing the index.\n",
      "        * list of ints or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3\n",
      "          each as a separate date column.\n",
      "        * list of lists. e.g.  If [[1, 3]] -> combine columns 1 and 3 and parse as\n",
      "          a single date column.\n",
      "        * dict, e.g. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call result\n",
      "          'foo'\n",
      "    \n",
      "        If a column or index contains an unparseable date, the entire column or\n",
      "        index will be returned unaltered as an object data type. For non-standard\n",
      "        datetime parsing, use ``pd.to_datetime`` after ``pd.read_csv``\n",
      "    \n",
      "        Note: A fast-path exists for iso8601-formatted dates.\n",
      "    infer_datetime_format : boolean, default False\n",
      "        If True and parse_dates is enabled, pandas will attempt to infer the format\n",
      "        of the datetime strings in the columns, and if it can be inferred, switch\n",
      "        to a faster method of parsing them. In some cases this can increase the\n",
      "        parsing speed by 5-10x.\n",
      "    keep_date_col : boolean, default False\n",
      "        If True and parse_dates specifies combining multiple columns then\n",
      "        keep the original columns.\n",
      "    date_parser : function, default None\n",
      "        Function to use for converting a sequence of string columns to an array of\n",
      "        datetime instances. The default uses ``dateutil.parser.parser`` to do the\n",
      "        conversion. Pandas will try to call date_parser in three different ways,\n",
      "        advancing to the next if an exception occurs: 1) Pass one or more arrays\n",
      "        (as defined by parse_dates) as arguments; 2) concatenate (row-wise) the\n",
      "        string values from the columns defined by parse_dates into a single array\n",
      "        and pass that; and 3) call date_parser once for each row using one or more\n",
      "        strings (corresponding to the columns defined by parse_dates) as arguments.\n",
      "    dayfirst : boolean, default False\n",
      "        DD/MM format dates, international and European format\n",
      "    iterator : boolean, default False\n",
      "        Return TextFileReader object for iteration or getting chunks with\n",
      "        ``get_chunk()``.\n",
      "    chunksize : int, default None\n",
      "        Return TextFileReader object for iteration.\n",
      "        See the `IO Tools docs\n",
      "        <http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_\n",
      "        for more information on ``iterator`` and ``chunksize``.\n",
      "    compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'\n",
      "        For on-the-fly decompression of on-disk data. If 'infer', then use gzip,\n",
      "        bz2, zip or xz if filepath_or_buffer is a string ending in '.gz', '.bz2',\n",
      "        '.zip', or 'xz', respectively, and no decompression otherwise. If using\n",
      "        'zip', the ZIP file must contain only one data file to be read in.\n",
      "        Set to None for no decompression.\n",
      "    \n",
      "        .. versionadded:: 0.18.1 support for 'zip' and 'xz' compression.\n",
      "    \n",
      "    thousands : str, default None\n",
      "        Thousands separator\n",
      "    decimal : str, default '.'\n",
      "        Character to recognize as decimal point (e.g. use ',' for European data).\n",
      "    float_precision : string, default None\n",
      "        Specifies which converter the C engine should use for floating-point\n",
      "        values. The options are `None` for the ordinary converter,\n",
      "        `high` for the high-precision converter, and `round_trip` for the\n",
      "        round-trip converter.\n",
      "    lineterminator : str (length 1), default None\n",
      "        Character to break file into lines. Only valid with C parser.\n",
      "    quotechar : str (length 1), optional\n",
      "        The character used to denote the start and end of a quoted item. Quoted\n",
      "        items can include the delimiter and it will be ignored.\n",
      "    quoting : int or csv.QUOTE_* instance, default 0\n",
      "        Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of\n",
      "        QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).\n",
      "    doublequote : boolean, default ``True``\n",
      "       When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate\n",
      "       whether or not to interpret two consecutive quotechar elements INSIDE a\n",
      "       field as a single ``quotechar`` element.\n",
      "    escapechar : str (length 1), default None\n",
      "        One-character string used to escape delimiter when quoting is QUOTE_NONE.\n",
      "    comment : str, default None\n",
      "        Indicates remainder of line should not be parsed. If found at the beginning\n",
      "        of a line, the line will be ignored altogether. This parameter must be a\n",
      "        single character. Like empty lines (as long as ``skip_blank_lines=True``),\n",
      "        fully commented lines are ignored by the parameter `header` but not by\n",
      "        `skiprows`. For example, if comment='#', parsing '#empty\\na,b,c\\n1,2,3'\n",
      "        with `header=0` will result in 'a,b,c' being\n",
      "        treated as the header.\n",
      "    encoding : str, default None\n",
      "        Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python\n",
      "        standard encodings\n",
      "        <https://docs.python.org/3/library/codecs.html#standard-encodings>`_\n",
      "    dialect : str or csv.Dialect instance, default None\n",
      "        If provided, this parameter will override values (default or not) for the\n",
      "        following parameters: `delimiter`, `doublequote`, `escapechar`,\n",
      "        `skipinitialspace`, `quotechar`, and `quoting`. If it is necessary to\n",
      "        override values, a ParserWarning will be issued. See csv.Dialect\n",
      "        documentation for more details.\n",
      "    tupleize_cols : boolean, default False\n",
      "        Leave a list of tuples on columns as is (default is to convert to\n",
      "        a Multi Index on the columns)\n",
      "    error_bad_lines : boolean, default True\n",
      "        Lines with too many fields (e.g. a csv line with too many commas) will by\n",
      "        default cause an exception to be raised, and no DataFrame will be returned.\n",
      "        If False, then these \"bad lines\" will dropped from the DataFrame that is\n",
      "        returned.\n",
      "    warn_bad_lines : boolean, default True\n",
      "        If error_bad_lines is False, and warn_bad_lines is True, a warning for each\n",
      "        \"bad line\" will be output.\n",
      "    low_memory : boolean, default True\n",
      "        Internally process the file in chunks, resulting in lower memory use\n",
      "        while parsing, but possibly mixed type inference.  To ensure no mixed\n",
      "        types either set False, or specify the type with the `dtype` parameter.\n",
      "        Note that the entire file is read into a single DataFrame regardless,\n",
      "        use the `chunksize` or `iterator` parameter to return the data in chunks.\n",
      "        (Only valid with C parser)\n",
      "    buffer_lines : int, default None\n",
      "        DEPRECATED: this argument will be removed in a future version because its\n",
      "        value is not respected by the parser\n",
      "    compact_ints : boolean, default False\n",
      "        DEPRECATED: this argument will be removed in a future version\n",
      "    \n",
      "        If compact_ints is True, then for any column that is of integer dtype,\n",
      "        the parser will attempt to cast it as the smallest integer dtype possible,\n",
      "        either signed or unsigned depending on the specification from the\n",
      "        `use_unsigned` parameter.\n",
      "    use_unsigned : boolean, default False\n",
      "        DEPRECATED: this argument will be removed in a future version\n",
      "    \n",
      "        If integer columns are being compacted (i.e. `compact_ints=True`), specify\n",
      "        whether the column should be compacted to the smallest signed or unsigned\n",
      "        integer dtype.\n",
      "    memory_map : boolean, default False\n",
      "        If a filepath is provided for `filepath_or_buffer`, map the file object\n",
      "        directly onto memory and access the data directly from there. Using this\n",
      "        option can improve performance because there is no longer any I/O overhead.\n",
      "    \n",
      "    Returns\n",
      "    -------\n",
      "    result : DataFrame or TextParser\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(pd.read_csv)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>This is an example CSV file</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>The text at the top here is not part of the da...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>to describe the file. You'll see this quite of...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>A -1 signifies a missing value.</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>year;London;Paris;Rome</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2001;7.322;2.148;2.547</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>2006;7.652;;2.627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2008;-1;2.211;</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>2009;-1;2.234;2.734</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>2011;8.174;;</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>2012;-1;2.244;2.627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>2015;8.615;;</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                          This is an example CSV file\n",
       "0   The text at the top here is not part of the da...\n",
       "1   to describe the file. You'll see this quite of...\n",
       "2                     A -1 signifies a missing value.\n",
       "3                              year;London;Paris;Rome\n",
       "4                              2001;7.322;2.148;2.547\n",
       "5                                   2006;7.652;;2.627\n",
       "6                                      2008;-1;2.211;\n",
       "7                                 2009;-1;2.234;2.734\n",
       "8                                        2011;8.174;;\n",
       "9                                 2012;-1;2.244;2.627\n",
       "10                                       2015;8.615;;"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_csv('city_pop.csv')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can see that by default it's done a fairly bad job of parsing the file (this is mostly because I;ve construsted the `city_pop.csv` file to be as obtuse as possible). It's making a lot of assumptions about the structure of the file but in general it's taking quite a naïve approach.\n",
    "\n",
    "The first this we notice is that it's treating the text at the top of the file as though it's data. Checking [the documentation](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html) we see that the simplest way to solve this is to use the `skiprows` argument to the function to which we give an integer giving the number of rows to skip:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>year;London;Paris;Rome</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2001;7.322;2.148;2.547</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2006;7.652;;2.627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2008;-1;2.211;</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2009;-1;2.234;2.734</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2011;8.174;;</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>2012;-1;2.244;2.627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2015;8.615;;</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   year;London;Paris;Rome\n",
       "0  2001;7.322;2.148;2.547\n",
       "1       2006;7.652;;2.627\n",
       "2          2008;-1;2.211;\n",
       "3     2009;-1;2.234;2.734\n",
       "4            2011;8.174;;\n",
       "5     2012;-1;2.244;2.627\n",
       "6            2015;8.615;;"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_csv(\n",
    "    'city_pop.csv',\n",
    "    skiprows=5,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The next most obvious problem is that it is not separating the columns at all. This is controlled by the `sep` argument which is set to `','` by default (hence *comma* separated values). We can simply set it to the appropriate semi-colon:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>year</th>\n",
       "      <th>London</th>\n",
       "      <th>Paris</th>\n",
       "      <th>Rome</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2001</td>\n",
       "      <td>7.322</td>\n",
       "      <td>2.148</td>\n",
       "      <td>2.547</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2006</td>\n",
       "      <td>7.652</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2008</td>\n",
       "      <td>-1.000</td>\n",
       "      <td>2.211</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2009</td>\n",
       "      <td>-1.000</td>\n",
       "      <td>2.234</td>\n",
       "      <td>2.734</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2011</td>\n",
       "      <td>8.174</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>2012</td>\n",
       "      <td>-1.000</td>\n",
       "      <td>2.244</td>\n",
       "      <td>2.627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2015</td>\n",
       "      <td>8.615</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   year  London  Paris   Rome\n",
       "0  2001   7.322  2.148  2.547\n",
       "1  2006   7.652    NaN  2.627\n",
       "2  2008  -1.000  2.211    NaN\n",
       "3  2009  -1.000  2.234  2.734\n",
       "4  2011   8.174    NaN    NaN\n",
       "5  2012  -1.000  2.244  2.627\n",
       "6  2015   8.615    NaN    NaN"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_csv(\n",
    "    'city_pop.csv',\n",
    "    skiprows=5,\n",
    "    sep=';'\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Reading the descriptive header of our data file we see that a value of `-1` signifies a missing reading so we should mark those too. This can be done after the fact but it is simplest to do it at import-time using the `na_values` argument:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>year</th>\n",
       "      <th>London</th>\n",
       "      <th>Paris</th>\n",
       "      <th>Rome</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2001</td>\n",
       "      <td>7.322</td>\n",
       "      <td>2.148</td>\n",
       "      <td>2.547</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2006</td>\n",
       "      <td>7.652</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2008</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.211</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2009</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.234</td>\n",
       "      <td>2.734</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2011</td>\n",
       "      <td>8.174</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>2012</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.244</td>\n",
       "      <td>2.627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2015</td>\n",
       "      <td>8.615</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   year  London  Paris   Rome\n",
       "0  2001   7.322  2.148  2.547\n",
       "1  2006   7.652    NaN  2.627\n",
       "2  2008     NaN  2.211    NaN\n",
       "3  2009     NaN  2.234  2.734\n",
       "4  2011   8.174    NaN    NaN\n",
       "5  2012     NaN  2.244  2.627\n",
       "6  2015   8.615    NaN    NaN"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_csv(\n",
    "    'city_pop.csv',\n",
    "    skiprows=5,\n",
    "    sep=';',\n",
    "    na_values='-1'\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last this we want to do is use the `year` column as the index for the `DataFrame`. This can be done by passing the name of the column to the `index_col` argument:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>London</th>\n",
       "      <th>Paris</th>\n",
       "      <th>Rome</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>year</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2001</th>\n",
       "      <td>7.322</td>\n",
       "      <td>2.148</td>\n",
       "      <td>2.547</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2006</th>\n",
       "      <td>7.652</td>\n",
       "      <td>NaN</td>\n",
       "      <td>2.627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2008</th>\n",
       "      <td>NaN</td>\n",
       "      <td>2.211</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2009</th>\n",
       "      <td>NaN</td>\n",
       "      <td>2.234</td>\n",
       "      <td>2.734</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2011</th>\n",
       "      <td>8.174</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2012</th>\n",
       "      <td>NaN</td>\n",
       "      <td>2.244</td>\n",
       "      <td>2.627</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2015</th>\n",
       "      <td>8.615</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      London  Paris   Rome\n",
       "year                      \n",
       "2001   7.322  2.148  2.547\n",
       "2006   7.652    NaN  2.627\n",
       "2008     NaN  2.211    NaN\n",
       "2009     NaN  2.234  2.734\n",
       "2011   8.174    NaN    NaN\n",
       "2012     NaN  2.244  2.627\n",
       "2015   8.615    NaN    NaN"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df3 = pd.read_csv(\n",
    "    'city_pop.csv',\n",
    "    skiprows=5,\n",
    "    sep=';',\n",
    "    na_values='-1',\n",
    "    index_col='year'\n",
    ")\n",
    "df3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise 4\n",
    "\n",
    "- Alongside `city_pop.csv` there is another file called `cetml1659on.dat` (also available from [here](https://raw.githubusercontent.com/milliams/data_analysis_python/master/cetml1659on.dat)). This contains some historical weather data for a location in the UK. Import that file as a Pandas `DataFrame` using `read_csv()`, making sure that you cover all the NaN values.\n",
    "- How many years had a negative average temperature in January?\n",
    "- What was the average temperature in June over the years in the data set? Tip: look in the [documentation](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html) for which method to call.\n",
    "\n",
    "We will come back to this data set in a later stage."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style>\n",
       "    .dataframe thead tr:only-child th {\n",
       "        text-align: right;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: left;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>JAN</th>\n",
       "      <th>FEB</th>\n",
       "      <th>MAR</th>\n",
       "      <th>APR</th>\n",
       "      <th>MAY</th>\n",
       "      <th>JUN</th>\n",
       "      <th>JUL</th>\n",
       "      <th>AUG</th>\n",
       "      <th>SEP</th>\n",
       "      <th>OCT</th>\n",
       "      <th>NOV</th>\n",
       "      <th>DEC</th>\n",
       "      <th>YEAR</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>1659</th>\n",
       "      <td>3.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>6.0</td>\n",
       "      <td>7.0</td>\n",
       "      <td>11.0</td>\n",
       "      <td>13.0</td>\n",
       "      <td>16.0</td>\n",
       "      <td>16.0</td>\n",
       "      <td>13.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>2.0</td>\n",
       "      <td>8.87</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1660</th>\n",
       "      <td>0.0</td>\n",
       "      <td>4.0</td>\n",
       "      <td>6.0</td>\n",
       "      <td>9.0</td>\n",
       "      <td>11.0</td>\n",
       "      <td>14.0</td>\n",
       "      <td>15.0</td>\n",
       "      <td>16.0</td>\n",
       "      <td>13.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>6.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>9.10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1661</th>\n",
       "      <td>5.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>6.0</td>\n",
       "      <td>8.0</td>\n",
       "      <td>11.0</td>\n",
       "      <td>14.0</td>\n",
       "      <td>15.0</td>\n",
       "      <td>15.0</td>\n",
       "      <td>13.0</td>\n",
       "      <td>11.0</td>\n",
       "      <td>8.0</td>\n",
       "      <td>6.0</td>\n",
       "      <td>9.78</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1662</th>\n",
       "      <td>5.0</td>\n",
       "      <td>6.0</td>\n",
       "      <td>6.0</td>\n",
       "      <td>8.0</td>\n",
       "      <td>11.0</td>\n",
       "      <td>15.0</td>\n",
       "      <td>15.0</td>\n",
       "      <td>15.0</td>\n",
       "      <td>13.0</td>\n",
       "      <td>11.0</td>\n",
       "      <td>6.0</td>\n",
       "      <td>3.0</td>\n",
       "      <td>9.52</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1663</th>\n",
       "      <td>1.0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>7.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>14.0</td>\n",
       "      <td>15.0</td>\n",
       "      <td>15.0</td>\n",
       "      <td>13.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>7.0</td>\n",
       "      <td>5.0</td>\n",
       "      <td>8.63</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "      JAN  FEB  MAR  APR   MAY   JUN   JUL   AUG   SEP   OCT  NOV  DEC  YEAR\n",
       "1659  3.0  4.0  6.0  7.0  11.0  13.0  16.0  16.0  13.0  10.0  5.0  2.0  8.87\n",
       "1660  0.0  4.0  6.0  9.0  11.0  14.0  15.0  16.0  13.0  10.0  6.0  5.0  9.10\n",
       "1661  5.0  5.0  6.0  8.0  11.0  14.0  15.0  15.0  13.0  11.0  8.0  6.0  9.78\n",
       "1662  5.0  6.0  6.0  8.0  11.0  15.0  15.0  15.0  13.0  11.0  6.0  3.0  9.52\n",
       "1663  1.0  1.0  5.0  7.0  10.0  14.0  15.0  15.0  13.0  10.0  7.0  5.0  8.63"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "weather = pd.read_csv(\n",
    "    'cetml1659on.dat',  # file name\n",
    "    skiprows=6,  # skip header\n",
    "    sep='\\s+',  # whitespace separated\n",
    "    na_values=['-99.9', '-99.99'],  # NaNs\n",
    ")\n",
    "weather.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "20"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "len(weather[weather.JAN < 0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14.325977653631282"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Answer\n",
    "\n",
    "weather.JUN.mean()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
