{
 "metadata": {
  "name": "",
  "signature": "sha256:6991d04b624b768016991b903af8eb06ea71e7459efecee94e205a7cff5e0fcd"
 },
 "nbformat": 3,
 "nbformat_minor": 0,
 "worksheets": [
  {
   "cells": [
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "# Who is the Greatest Commander in the War of Five Kings?\n",
      "\n",
      "- By Chris Albon (@ChrisAlbon)\n",
      "- Date: December 8, 2014\n",
      "- Description: Find out who is the greatest commander in the The War of Five Kings.\n",
      "- Dataset: [Battles in the War of Five Kings](https://github.com/chrisalbon/war_of_the_five_kings_dataset)"
     ]
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "## Preliminaries"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Import required modules\n",
      "import pandas as pd\n",
      "from ggplot import *\n",
      "import numpy as np\n",
      "%matplotlib inline\n",
      "\n",
      "# Set ipython's max row display\n",
      "pd.set_option('display.max_row', 1000)\n",
      "\n",
      "# Set iPython's max column width to 50\n",
      "pd.set_option('display.max_columns', 50)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 1
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Load the dataset\n",
      "df = pd.read_csv('5kings_battles_v1.csv')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 2
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "## Quick glance at the data"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# View the top 3 rows\n",
      "df.head(3)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "html": [
        "<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
        "<table border=\"1\" class=\"dataframe\">\n",
        "  <thead>\n",
        "    <tr style=\"text-align: right;\">\n",
        "      <th></th>\n",
        "      <th>name</th>\n",
        "      <th>year</th>\n",
        "      <th>battle_number</th>\n",
        "      <th>attacker_king</th>\n",
        "      <th>defender_king</th>\n",
        "      <th>attacker_1</th>\n",
        "      <th>attacker_2</th>\n",
        "      <th>attacker_3</th>\n",
        "      <th>attacker_4</th>\n",
        "      <th>defender_1</th>\n",
        "      <th>defender_2</th>\n",
        "      <th>defender_3</th>\n",
        "      <th>defender_4</th>\n",
        "      <th>attacker_outcome</th>\n",
        "      <th>battle_type</th>\n",
        "      <th>major_death</th>\n",
        "      <th>major_capture</th>\n",
        "      <th>attacker_size</th>\n",
        "      <th>defender_size</th>\n",
        "      <th>attacker_commander</th>\n",
        "      <th>defender_commander</th>\n",
        "      <th>summer</th>\n",
        "      <th>location</th>\n",
        "      <th>region</th>\n",
        "      <th>note</th>\n",
        "    </tr>\n",
        "  </thead>\n",
        "  <tbody>\n",
        "    <tr>\n",
        "      <th>0</th>\n",
        "      <td>  Battle of the Golden Tooth</td>\n",
        "      <td> 298</td>\n",
        "      <td> 1</td>\n",
        "      <td> Joffrey/Tommen Baratheon</td>\n",
        "      <td> Robb Stark</td>\n",
        "      <td> Lannister</td>\n",
        "      <td> NaN</td>\n",
        "      <td> NaN</td>\n",
        "      <td> NaN</td>\n",
        "      <td>     Tully</td>\n",
        "      <td> NaN</td>\n",
        "      <td>NaN</td>\n",
        "      <td>NaN</td>\n",
        "      <td> win</td>\n",
        "      <td> pitched battle</td>\n",
        "      <td> 1</td>\n",
        "      <td> 0</td>\n",
        "      <td> 15000</td>\n",
        "      <td>  4000</td>\n",
        "      <td>              Jaime Lannister</td>\n",
        "      <td>          Clement Piper, Vance</td>\n",
        "      <td> 1</td>\n",
        "      <td>  Golden Tooth</td>\n",
        "      <td> The Westerlands</td>\n",
        "      <td> NaN</td>\n",
        "    </tr>\n",
        "    <tr>\n",
        "      <th>1</th>\n",
        "      <td> Battle at the Mummer's Ford</td>\n",
        "      <td> 298</td>\n",
        "      <td> 2</td>\n",
        "      <td> Joffrey/Tommen Baratheon</td>\n",
        "      <td> Robb Stark</td>\n",
        "      <td> Lannister</td>\n",
        "      <td> NaN</td>\n",
        "      <td> NaN</td>\n",
        "      <td> NaN</td>\n",
        "      <td> Baratheon</td>\n",
        "      <td> NaN</td>\n",
        "      <td>NaN</td>\n",
        "      <td>NaN</td>\n",
        "      <td> win</td>\n",
        "      <td>         ambush</td>\n",
        "      <td> 1</td>\n",
        "      <td> 0</td>\n",
        "      <td>   NaN</td>\n",
        "      <td>   120</td>\n",
        "      <td>               Gregor Clegane</td>\n",
        "      <td>              Beric Dondarrion</td>\n",
        "      <td> 1</td>\n",
        "      <td> Mummer's Ford</td>\n",
        "      <td>  The Riverlands</td>\n",
        "      <td> NaN</td>\n",
        "    </tr>\n",
        "    <tr>\n",
        "      <th>2</th>\n",
        "      <td>          Battle of Riverrun</td>\n",
        "      <td> 298</td>\n",
        "      <td> 3</td>\n",
        "      <td> Joffrey/Tommen Baratheon</td>\n",
        "      <td> Robb Stark</td>\n",
        "      <td> Lannister</td>\n",
        "      <td> NaN</td>\n",
        "      <td> NaN</td>\n",
        "      <td> NaN</td>\n",
        "      <td>     Tully</td>\n",
        "      <td> NaN</td>\n",
        "      <td>NaN</td>\n",
        "      <td>NaN</td>\n",
        "      <td> win</td>\n",
        "      <td> pitched battle</td>\n",
        "      <td> 0</td>\n",
        "      <td> 1</td>\n",
        "      <td> 15000</td>\n",
        "      <td> 10000</td>\n",
        "      <td> Jaime Lannister, Andros Brax</td>\n",
        "      <td> Edmure Tully, Tytos Blackwood</td>\n",
        "      <td> 1</td>\n",
        "      <td>      Riverrun</td>\n",
        "      <td>  The Riverlands</td>\n",
        "      <td> NaN</td>\n",
        "    </tr>\n",
        "  </tbody>\n",
        "</table>\n",
        "</div>"
       ],
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 30,
       "text": [
        "                          name  year  battle_number             attacker_king  \\\n",
        "0   Battle of the Golden Tooth   298              1  Joffrey/Tommen Baratheon   \n",
        "1  Battle at the Mummer's Ford   298              2  Joffrey/Tommen Baratheon   \n",
        "2           Battle of Riverrun   298              3  Joffrey/Tommen Baratheon   \n",
        "\n",
        "  defender_king attacker_1 attacker_2 attacker_3 attacker_4 defender_1  \\\n",
        "0    Robb Stark  Lannister        NaN        NaN        NaN      Tully   \n",
        "1    Robb Stark  Lannister        NaN        NaN        NaN  Baratheon   \n",
        "2    Robb Stark  Lannister        NaN        NaN        NaN      Tully   \n",
        "\n",
        "  defender_2  defender_3  defender_4 attacker_outcome     battle_type  \\\n",
        "0        NaN         NaN         NaN              win  pitched battle   \n",
        "1        NaN         NaN         NaN              win          ambush   \n",
        "2        NaN         NaN         NaN              win  pitched battle   \n",
        "\n",
        "   major_death  major_capture  attacker_size  defender_size  \\\n",
        "0            1              0          15000           4000   \n",
        "1            1              0            NaN            120   \n",
        "2            0              1          15000          10000   \n",
        "\n",
        "             attacker_commander             defender_commander  summer  \\\n",
        "0               Jaime Lannister           Clement Piper, Vance       1   \n",
        "1                Gregor Clegane               Beric Dondarrion       1   \n",
        "2  Jaime Lannister, Andros Brax  Edmure Tully, Tytos Blackwood       1   \n",
        "\n",
        "        location           region note  \n",
        "0   Golden Tooth  The Westerlands  NaN  \n",
        "1  Mummer's Ford   The Riverlands  NaN  \n",
        "2       Riverrun   The Riverlands  NaN  "
       ]
      }
     ],
     "prompt_number": 30
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "## Data wrangling"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Create a list of attacking commanders\n",
      "attacker_list = []\n",
      "\n",
      "# For each row in df.attacker_commander,\n",
      "for row in df['attacker_commander']:\n",
      "    # if the cell is a string,\n",
      "    if type(row) == str:\n",
      "        # split up the names by the comma, \n",
      "        #and attach it to attacker commander list,\n",
      "       attacker_list.append(row.split(','))\n",
      "    # otherwise,     \n",
      "    else:\n",
      "        # do nothing\n",
      "        continue\n",
      "\n",
      "# Create a list of defending commanders\n",
      "defender_list = []\n",
      "        \n",
      "# For each row in df.defender_commander,\n",
      "for row in df['defender_commander']:\n",
      "    # if the cell is a string,\n",
      "    if type(row) == str:\n",
      "        # split up the names by the comma, \n",
      "        #and attach it to defender commander list,\n",
      "       defender_list.append(row.split(','))\n",
      "    # otherwise\n",
      "    else:\n",
      "        # do nothing\n",
      "        defender_list.append('')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 4
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Create a list of commanders\n",
      "commander = []\n",
      "\n",
      "# For each list in attacker_list,\n",
      "for row in attacker_list:\n",
      "    # and each list in that list\n",
      "    for element in row:\n",
      "        # strip of any leading blank space \n",
      "        # and append it to the commander list\n",
      "        commander.append(element.lstrip())\n",
      "\n",
      "# For each list in defender_list,\n",
      "for row in defender_list:\n",
      "    # and each list in that list\n",
      "    for element in row:\n",
      "        # strip of any leading blank space \n",
      "        # and append it to the commander list\n",
      "        commander.append(element.lstrip())"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 5
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Convert the commander list into a \n",
      "# set of unique names, and convert it to a list\n",
      "commanders = list(set(commander))\n",
      "\n",
      "# Display the total number of commanders in the list\n",
      "len(commanders)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 44,
       "text": [
        "82"
       ]
      }
     ],
     "prompt_number": 44
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#  Count the number of times a commander successfully attacked\n",
      "\n",
      "# Create a list\n",
      "attack_win = []\n",
      "\n",
      "# for each commander:\n",
      "for row in commanders:\n",
      "    # create a score variable, then\n",
      "    score = 0\n",
      "    # go through each cell of attacker commander where the attacker wins:\n",
      "    for x in df['attacker_commander'][df['attacker_outcome'] == 'win']:\n",
      "        # if the cell is a string\n",
      "        if type(x) == str:\n",
      "            # and if the commander is in the cell\n",
      "            if row in x:\n",
      "                # add one to score\n",
      "                score = score + 1\n",
      "            # if not\n",
      "            else:\n",
      "                # add 0 to score\n",
      "                score = score + 0\n",
      "        # if the cell is not a string        \n",
      "        else:\n",
      "            # do nothing\n",
      "            continue\n",
      "    # append the score to the list\n",
      "    attack_win.append(score)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 7
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#  Count the number of times a commander unsuccessfully attacked\n",
      "\n",
      "# Create a list\n",
      "attack_loss = []\n",
      "\n",
      "# for each commander:\n",
      "for row in commanders:\n",
      "    # create a score variable\n",
      "    score = 0\n",
      "    # go through each cell of attacker commander where the attacker loses:\n",
      "    for x in df['attacker_commander'][df['attacker_outcome'] == 'loss']:\n",
      "        # if the cell is a string\n",
      "        if type(x) == str:\n",
      "            # and if the commander is in the cell\n",
      "            if row in x:\n",
      "                # add one to score\n",
      "                score = score + 1\n",
      "            # if not\n",
      "            else:\n",
      "                # add 0 to score\n",
      "                score = score + 0\n",
      "        # if the cell is not a string        \n",
      "        else:\n",
      "            # do nothing\n",
      "            continue\n",
      "    # append the score to the list\n",
      "    attack_loss.append(score)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 8
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#  Count the number of times a commander successfully defended\n",
      "\n",
      "# Create a list\n",
      "defend_win = []\n",
      "\n",
      "# for each commander:\n",
      "for row in commanders:\n",
      "    # create a score variable\n",
      "    score = 0\n",
      "    # go through each cell of defender commander where the attacker losses:\n",
      "    for x in df['defender_commander'][df['attacker_outcome'] == 'loss']:\n",
      "        # if the cell is a string\n",
      "        if type(x) == str:\n",
      "            # and if the commander is in the cell\n",
      "            if row in x:\n",
      "                # add one to score\n",
      "                score = score + 1\n",
      "            # if not\n",
      "            else:\n",
      "                # add 0 to score\n",
      "                score = score + 0\n",
      "        # if the cell is not a string        \n",
      "        else:\n",
      "            # do nothing\n",
      "            continue   \n",
      "    # append the score to the list\n",
      "    defend_win.append(score)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 9
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "#  Count the number of times a commander unsuccessfully defended\n",
      "\n",
      "# Create a list\n",
      "defend_loss = []\n",
      "\n",
      "# for each commander:\n",
      "for row in commanders:\n",
      "    # create a score variable\n",
      "    score = 0\n",
      "    # go through each cell of defender commander where the attacker wins:\n",
      "    for x in df['defender_commander'][df['attacker_outcome'] == 'win']:\n",
      "        # if the cell is a string\n",
      "        if type(x) == str:\n",
      "            # and if the commander is in the cell\n",
      "            if row in x:\n",
      "                # add one to score\n",
      "                score = score + 1\n",
      "            # if not\n",
      "            else:\n",
      "                # add 0 to score\n",
      "                score = score + 0\n",
      "        # if the cell is not a string        \n",
      "        else:\n",
      "            # do nothing\n",
      "            continue\n",
      "    # append the score to the list\n",
      "    defend_loss.append(score)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 10
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Create a dictionary of the four score lists\n",
      "columns = {'attack_win':  attack_win, \n",
      "           'attack_loss': attack_loss,\n",
      "           'defend_win': defend_win,\n",
      "           'defend_loss': attack_loss}\n",
      "\n",
      "# Create a dataframe from that dictionary, indexed by a commander's name\n",
      "battle_record = pd.DataFrame(columns, index=commanders)"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 11
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Count the total attacks for for each commander\n",
      "battle_record['total_attacks'] = battle_record['attack_win'] + battle_record['attack_loss']\n",
      "\n",
      "# Count the total defends for for each commander\n",
      "battle_record['total_defends'] = battle_record['defend_win'] + battle_record['defend_loss']\n",
      "\n",
      "# Count the total wins for for each commander\n",
      "battle_record['total_wins'] = battle_record['attack_win'] + battle_record['defend_win']\n",
      "\n",
      "# Count the total losses for for each commander\n",
      "battle_record['total_loss'] = battle_record['attack_loss'] + battle_record['defend_loss']\n",
      "\n",
      "# Create a total number of battles for each commander\n",
      "battle_record['total_battles'] = battle_record['attack_win'] + battle_record['attack_loss'] + battle_record['defend_win'] + battle_record['defend_loss']\n",
      "\n",
      "# Create a win percentage score (total wins / total battles) for each commander\n",
      "battle_record['win_percentage'] = battle_record['total_wins'] / battle_record['total_battles'] * 100\n",
      "\n",
      "# Create a composite score (total number of wins minus total number of losses) for each commander\n",
      "battle_record['composite_record'] = (battle_record['attack_win'] + battle_record['defend_win']) - (battle_record['attack_loss'] + battle_record['defend_loss'])"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 32
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "## Analysis"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Top 10 Most Active Commanders\n",
      "battle_record.sort('total_battles', ascending=False).head(10)['total_battles']"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 17,
       "text": [
        "Gregor Clegane       8\n",
        "Stannis Baratheon    5\n",
        "Tywin Lannister      4\n",
        "Robb Stark           4\n",
        "Roose Bolton         4\n",
        "Jaime Lannister      4\n",
        "Victarion Greyjoy    3\n",
        "Addam Marbrand       3\n",
        "Brynden Tully        3\n",
        "Davos Seaworth       3\n",
        "Name: total_battles, dtype: int64"
       ]
      }
     ],
     "prompt_number": 17
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Top 10 Most Active Attackers\n",
      "battle_record.sort('total_attacks', ascending=False).head(10)['total_attacks']"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 18,
       "text": [
        "Gregor Clegane       5\n",
        "Jaime Lannister      4\n",
        "Robb Stark           4\n",
        "Theon Greyjoy        3\n",
        "Brynden Tully        3\n",
        "Roose Bolton         3\n",
        "Stannis Baratheon    3\n",
        "Walder Frey          3\n",
        "Victarion Greyjoy    3\n",
        "Euron Greyjoy        2\n",
        "Name: total_attacks, dtype: int64"
       ]
      }
     ],
     "prompt_number": 18
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Top 10 Most Active Defenders\n",
      "battle_record.sort('total_defends', ascending=False).head(10)['total_defends']"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 19,
       "text": [
        "Tywin Lannister      3\n",
        "Gregor Clegane       3\n",
        "Addam Marbrand       2\n",
        "Stannis Baratheon    2\n",
        "Randyll Tarly        2\n",
        "Kevan Lannister      1\n",
        "Cotter Pyke          1\n",
        "Roose Bolton         1\n",
        "Flement Brax         1\n",
        "Halys Hornwood       1\n",
        "Name: total_defends, dtype: int64"
       ]
      }
     ],
     "prompt_number": 19
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Top 10 Most Victorious Commanders\n",
      "battle_record.sort('total_wins', ascending=False).head(10)['total_wins']"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 20,
       "text": [
        "Gregor Clegane       6\n",
        "Robb Stark           4\n",
        "Jaime Lannister      4\n",
        "Victarion Greyjoy    3\n",
        "Stannis Baratheon    3\n",
        "Brynden Tully        3\n",
        "Walder Frey          3\n",
        "Theon Greyjoy        3\n",
        "Mace Tyrell          2\n",
        "Tywin Lannister      2\n",
        "Name: total_wins, dtype: int64"
       ]
      }
     ],
     "prompt_number": 20
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Top 30 Most Losing Commanders\n",
      "battle_record.sort('total_loss', ascending=False).head(30)['total_loss']"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 33,
       "text": [
        "Lyle Crakehall        2\n",
        "Davos Seaworth        2\n",
        "Robertt Glover        2\n",
        "Harrion Karstark      2\n",
        "Harma Dogshead        2\n",
        "Magnar Styr           2\n",
        "Guyard Morrigen       2\n",
        "Roose Bolton          2\n",
        "Wylis Manderly        2\n",
        "Rolland Storm         2\n",
        "Stannis Baratheon     2\n",
        "Flement Brax          2\n",
        "Tywin Lannister       2\n",
        "Addam Marbrand        2\n",
        "Gregor Clegane        2\n",
        "Imry Florent          2\n",
        "Tormund Giantsbane    2\n",
        "Medger Cerwyn         2\n",
        "Halys Hornwood        2\n",
        "Varamyr               2\n",
        "Helman Tallhart       2\n",
        "Leo Lefford           2\n",
        "Salladhor Saan        2\n",
        "Mance Rayder          2\n",
        "Randyll Tarly         0\n",
        "Walder Rivers         0\n",
        "Robb Stark            0\n",
        "Cotter Pyke           0\n",
        "Raxter Redwyne        0\n",
        "Dagmer Cleftjaw       0\n",
        "Name: total_loss, dtype: int64"
       ]
      }
     ],
     "prompt_number": 33
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Commanders With The Best Win Percentage\n",
      "battle_record.sort('win_percentage', ascending=False).head(75)['win_percentage'][battle_record['win_percentage'] != float('Inf')]"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 42,
       "text": [
        "Tyrion Lannister     100.000000\n",
        "Raxter Redwyne       100.000000\n",
        "Black Walder Frey    100.000000\n",
        "Jon Snow             100.000000\n",
        "Walder Rivers        100.000000\n",
        "Robb Stark           100.000000\n",
        "Brynden Tully        100.000000\n",
        "Kevan Lannister      100.000000\n",
        "Randyll Tarly        100.000000\n",
        "Theon Greyjoy        100.000000\n",
        "Euron Greyjoy        100.000000\n",
        "Cotter Pyke          100.000000\n",
        "Donal Noye           100.000000\n",
        "Jonos Bracken        100.000000\n",
        "Vance                100.000000\n",
        "Sandor Clegane       100.000000\n",
        "Cley Cerwyn          100.000000\n",
        "Smalljon Umber       100.000000\n",
        "Garlan Tyrell        100.000000\n",
        "Vargo Hoat           100.000000\n",
        "Ryman Fey            100.000000\n",
        "Dagmer Cleftjaw      100.000000\n",
        "Edmure Tully         100.000000\n",
        "Tytos Blackwood      100.000000\n",
        "Karyl Vance          100.000000\n",
        "Ramsey Bolton        100.000000\n",
        "Victarion Greyjoy    100.000000\n",
        "Loras Tyrell         100.000000\n",
        "Jaime Lannister      100.000000\n",
        "Walder Frey          100.000000\n",
        "Mathis Rowan         100.000000\n",
        "Ramsay Snow          100.000000\n",
        "Rodrik Cassel        100.000000\n",
        "Jason Mallister      100.000000\n",
        "Asha Greyjoy         100.000000\n",
        "Mace Tyrell          100.000000\n",
        "Rorge                100.000000\n",
        "Daven Lannister      100.000000\n",
        "Alysane Mormot       100.000000\n",
        "Jacelyn Bywater      100.000000\n",
        "Robett Glover        100.000000\n",
        "Andros Brax          100.000000\n",
        "Theon Greyjoy        100.000000\n",
        "Gregor Clegane        75.000000\n",
        "Stannis Baratheon     60.000000\n",
        "Tywin Lannister       50.000000\n",
        "Roose Bolton          50.000000\n",
        "Helman Tallhart       33.333333\n",
        "Davos Seaworth        33.333333\n",
        "Addam Marbrand        33.333333\n",
        "Salladhor Saan         0.000000\n",
        "Mance Rayder           0.000000\n",
        "Medger Cerwyn          0.000000\n",
        "Lyle Crakehall         0.000000\n",
        "Leo Lefford            0.000000\n",
        "Flement Brax           0.000000\n",
        "Varamyr                0.000000\n",
        "Guyard Morrigen        0.000000\n",
        "Magnar Styr            0.000000\n",
        "Harma Dogshead         0.000000\n",
        "Name: win_percentage, Length: 60, dtype: float64"
       ]
      }
     ],
     "prompt_number": 42
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Top 10 Greatest Commanders\n",
      "battle_record.sort('composite_record', ascending=False).head(10)['composite_record']"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 34,
       "text": [
        "Robb Stark           4\n",
        "Jaime Lannister      4\n",
        "Gregor Clegane       4\n",
        "Walder Frey          3\n",
        "Brynden Tully        3\n",
        "Victarion Greyjoy    3\n",
        "Theon Greyjoy        3\n",
        "Mace Tyrell          2\n",
        "Randyll Tarly        2\n",
        "Euron Greyjoy        2\n",
        "Name: composite_record, dtype: int64"
       ]
      }
     ],
     "prompt_number": 34
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "## A little more data wrangling for the tie-breaker"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Create a list with the defender/attacker \n",
      "# ratios for each battle Jaime Lannister fought\n",
      "jaime_ratio = []\n",
      "\n",
      "# Create a list with the defender/attacker \n",
      "# ratios for each battle Robb Stark fought\n",
      "robb_ratio = []\n",
      "\n",
      "# Create a list with the defender/attacker \n",
      "# ratios for each battle Gregor Clegane fought\n",
      "gregor_ratio = []\n",
      "\n",
      "# Create a count variable\n",
      "i = 0\n",
      "\n",
      "# For each row in df.attacker_commander where the attacker wins,\n",
      "for row in df['attacker_commander'][df['attacker_outcome'] == 'win']:\n",
      "        # if the row is a string (this means we skip np.nan's, which are floats)\n",
      "        if type(row) == str:\n",
      "            # if the row contains this name\n",
      "            if \"Jaime Lannister\" in row:\n",
      "                # divide the size of the defender's army with the size of the attacker's army\n",
      "                relative_size = df['defender_size'][i] / df['attacker_size'][i]\n",
      "                jaime_ratio.append(relative_size)\n",
      "            # if the row contains this name\n",
      "            elif \"Robb Stark\" in row:\n",
      "                # divide the size of the defender's army with the size of the attacker's army\n",
      "                relative_size = df['defender_size'][i] / df['attacker_size'][i]\n",
      "                robb_ratio.append(relative_size)\n",
      "            # if the row contains this name\n",
      "            elif \"Gregor Clegane\" in row:\n",
      "                # divide the size of the defender's army with the size of the attacker's army\n",
      "                relative_size = df['defender_size'][i] / df['attacker_size'][i]\n",
      "                gregor_ratio.append(relative_size)\n",
      "            # otherwise\n",
      "            else:\n",
      "                # do nothing\n",
      "                continue\n",
      "        \n",
      "        # and add 1 to the counter variable\n",
      "        i = i+1\n"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 24
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Create an empty dataframe\n",
      "top3_ratio = pd.DataFrame()\n",
      "\n",
      "# Create three columns for the dataframe for each commander's ratios\n",
      "top3_ratio['jaime'] = jaime_ratio\n",
      "top3_ratio['robb'] = robb_ratio\n",
      "top3_ratio['gregor'] = gregor_ratio"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [],
     "prompt_number": 25
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Display the ratios of each commander's four battles\n",
      "top3_ratio"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "html": [
        "<div style=\"max-height:1000px;max-width:1500px;overflow:auto;\">\n",
        "<table border=\"1\" class=\"dataframe\">\n",
        "  <thead>\n",
        "    <tr style=\"text-align: right;\">\n",
        "      <th></th>\n",
        "      <th>jaime</th>\n",
        "      <th>robb</th>\n",
        "      <th>gregor</th>\n",
        "    </tr>\n",
        "  </thead>\n",
        "  <tbody>\n",
        "    <tr>\n",
        "      <th>0</th>\n",
        "      <td> 0.266667</td>\n",
        "      <td> 1.111111</td>\n",
        "      <td>      NaN</td>\n",
        "    </tr>\n",
        "    <tr>\n",
        "      <th>1</th>\n",
        "      <td> 0.666667</td>\n",
        "      <td> 3.200000</td>\n",
        "      <td> 2.104167</td>\n",
        "    </tr>\n",
        "    <tr>\n",
        "      <th>2</th>\n",
        "      <td>      NaN</td>\n",
        "      <td>      NaN</td>\n",
        "      <td>      NaN</td>\n",
        "    </tr>\n",
        "    <tr>\n",
        "      <th>3</th>\n",
        "      <td>      NaN</td>\n",
        "      <td>      NaN</td>\n",
        "      <td> 3.688525</td>\n",
        "    </tr>\n",
        "  </tbody>\n",
        "</table>\n",
        "</div>"
       ],
       "metadata": {},
       "output_type": "pyout",
       "prompt_number": 38,
       "text": [
        "      jaime      robb    gregor\n",
        "0  0.266667  1.111111       NaN\n",
        "1  0.666667  3.200000  2.104167\n",
        "2       NaN       NaN       NaN\n",
        "3       NaN       NaN  3.688525"
       ]
      }
     ],
     "prompt_number": 38
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "## Tie-breaker results"
     ]
    },
    {
     "cell_type": "code",
     "collapsed": false,
     "input": [
      "# Print a plain English sentence that includes the mean ratio (rounded to two decimals)\n",
      "print('On average, Jaime Lannister successfully attacked when the enemy has', top3_ratio['jaime'].mean().round(2), 'soldiers for every one of his own.')\n",
      "\n",
      "# Print a plain English sentence that includes the mean ratio (rounded to two decimals)\n",
      "print('On average, Robb Stark successfully attacked when the enemy has', top3_ratio['robb'].mean().round(2), 'soldiers for every one of his own.')\n",
      "\n",
      "# Print a plain English sentence that includes the mean ratio (rounded to two decimals)\n",
      "print('On average, Gregor Clegane successfully attacked when the enemy has', top3_ratio['gregor'].mean().round(2), 'soldiers for every one of his own.')"
     ],
     "language": "python",
     "metadata": {},
     "outputs": [
      {
       "output_type": "stream",
       "stream": "stdout",
       "text": [
        "On average, Jaime Lannister successfully attacked when the enemy has 0.47 soldiers for every one of his own.\n",
        "On average, Robb Stark successfully attacked when the enemy has 2.16 soldiers for every one of his own.\n",
        "On average, Gregor Clegane successfully attacked when the enemy has 2.9 soldiers for every one of his own.\n"
       ]
      }
     ],
     "prompt_number": 41
    },
    {
     "cell_type": "markdown",
     "metadata": {},
     "source": [
      "### And the greatest commander is: Gregor Clegane"
     ]
    }
   ],
   "metadata": {}
  }
 ]
}