{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Augment data from TSV files to change team names and years" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create dictionary for mapping team names and abbreviations" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "30\n", "30\n", "30\n", "30\n", "0,Atlanta Hawks,0,ATL,0\n", "1,Boston Celtics,1,BOS,1\n", "2,Cleveland Cavaliers,2,CLE,2\n", "3,New Orleans Pelicans,3,NOP,3\n", "4,Chicago Bulls,4,CHI,4\n", "5,Dallas Mavericks,5,DAL,5\n", "6,Denver Nuggets,6,DEN,6\n", "7,Golden State Warriors,7,GSW,7\n", "8,Houston Rockets,8,HOU,8\n", "9,Los Angeles Clippers,9,LAC,9\n", "10,Los Angeles Lakers,10,LAL,10\n", "11,Miami Heat,11,MIA,11\n", "12,Milwaukee Bucks,12,MIL,12\n", "13,Minnesota Timberwolves,13,MIN,13\n", "14,Brooklyn Nets,14,BKN,14\n", "15,New York Knicks,15,NYK,15\n", "16,Orlando Magic,16,ORL,16\n", "17,Indiana Pacers,17,IND,17\n", "18,Philadelphia 76ers,18,PHI,18\n", "19,Phoenix Suns,19,PHX,19\n", "20,Portland Trail Blazers,20,POR,20\n", "21,Sacramento Kings,21,SAC,21\n", "22,San Antonio Spurs,22,SAS,22\n", "23,Oklahoma City Thunder,23,OKC,23\n", "24,Toronto Raptors,24,TOR,24\n", "25,Utah Jazz,25,UTA,25\n", "26,Memphis Grizzlies,26,MEM,26\n", "27,Washington Wizards,27,WAS,27\n", "28,Detroit Pistons,28,DET,28\n", "29,Charlotte Hornets,29,CHA,29\n" ] } ], "source": [ "# Create team map and team array\n", "team_map = {\n", " \"Atlanta Hawks\": 0,\n", " \"Boston Celtics\": 1,\n", " \"Cleveland Cavaliers\": 2,\n", " \"New Orleans Pelicans\": 3,\n", " \"Chicago Bulls\": 4,\n", " \"Dallas Mavericks\": 5,\n", " \"Denver Nuggets\": 6,\n", " \"Golden State Warriors\": 7,\n", " \"Houston Rockets\": 8,\n", " \"Los Angeles Clippers\": 9,\n", " \"Los Angeles Lakers\": 10,\n", " \"Miami Heat\": 11,\n", " \"Milwaukee Bucks\": 12,\n", " \"Minnesota Timberwolves\": 13,\n", " \"Brooklyn Nets\": 14,\n", " \"New York Knicks\": 15,\n", " \"Orlando Magic\": 16,\n", " \"Indiana Pacers\": 17,\n", " \"Philadelphia 76ers\": 18,\n", " \"Phoenix Suns\": 19,\n", " \"Portland Trail Blazers\": 20,\n", " \"Sacramento Kings\": 21,\n", " \"San Antonio Spurs\": 22,\n", " \"Oklahoma City Thunder\": 23,\n", " \"Toronto Raptors\": 24,\n", " \"Utah Jazz\": 25,\n", " \"Memphis Grizzlies\": 26,\n", " \"Washington Wizards\": 27,\n", " \"Detroit Pistons\": 28,\n", " \"Charlotte Hornets\": 29\n", "}\n", "\n", "team_array = [\n", "\"Atlanta Hawks\",\n", "\"Boston Celtics\",\n", "\"Cleveland Cavaliers\",\n", "\"New Orleans Pelicans\",\n", "\"Chicago Bulls\",\n", "\"Dallas Mavericks\",\n", "\"Denver Nuggets\",\n", "\"Golden State Warriors\",\n", "\"Houston Rockets\",\n", "\"Los Angeles Clippers\",\n", "\"Los Angeles Lakers\",\n", "\"Miami Heat\",\n", "\"Milwaukee Bucks\",\n", "\"Minnesota Timberwolves\",\n", "\"Brooklyn Nets\",\n", "\"New York Knicks\",\n", "\"Orlando Magic\",\n", "\"Indiana Pacers\",\n", "\"Philadelphia 76ers\",\n", "\"Phoenix Suns\",\n", "\"Portland Trail Blazers\",\n", "\"Sacramento Kings\",\n", "\"San Antonio Spurs\",\n", "\"Oklahoma City Thunder\",\n", "\"Toronto Raptors\",\n", "\"Utah Jazz\",\n", "\"Memphis Grizzlies\",\n", "\"Washington Wizards\",\n", "\"Detroit Pistons\",\n", "\"Charlotte Hornets\"]\n", "\n", "# Check that array and dictionary are aligned properly\n", "for i in range(len(team_array)):\n", " if i != team_map[team_array[i]]:\n", " print(\"Invalid!\")\n", "\n", "# Create abbreviation map and array\n", "abbreviation_array = [\n", "\"ATL\",\n", "\"BOS\",\n", "\"CLE\",\n", "\"NOP\",\n", "\"CHI\",\n", "\"DAL\",\n", "\"DEN\",\n", "\"GSW\",\n", "\"HOU\",\n", "\"LAC\",\n", "\"LAL\",\n", "\"MIA\",\n", "\"MIL\",\n", "\"MIN\",\n", "\"BKN\",\n", "\"NYK\",\n", "\"ORL\",\n", "\"IND\",\n", "\"PHI\",\n", "\"PHX\",\n", "\"POR\",\n", "\"SAC\",\n", "\"SAS\",\n", "\"OKC\",\n", "\"TOR\",\n", "\"UTA\",\n", "\"MEM\",\n", "\"WAS\",\n", "\"DET\",\n", "\"CHA\"]\n", "\n", "abbreviation_map = {}\n", "for i in range(len(abbreviation_array)):\n", " abbreviation_map[abbreviation_array[i]] = i\n", "\n", "print(len(team_array))\n", "print(len(team_map))\n", "print(len(abbreviation_array))\n", "print(len(abbreviation_map))\n", "\n", "# Check that team names, abbreviation and index maps all line up\n", "for i in range(len(team_array)):\n", " print(str(i) + \",\" + team_array[i] + \",\" + str(team_map[team_array[i]]) + \",\" + abbreviation_array[i] + \",\" + str(abbreviation_map[abbreviation_array[i]]))\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create function to augment data by updating team names in SQL queries" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [ "import random\n", "import pandas as pd\n", "import sqlite3 as sql\n", "\n", "# Find team names in the sample\n", "def find_teams_in_sample(sample, team_list):\n", " result = []\n", " for i in range(len(team_list)):\n", " if team_list[i] in sample:\n", " result.append(i)\n", " return result\n", "\n", "# Get random number excluding the one already used\n", "def get_random_excluding(floor, ceiling, excluded_number):\n", " number = random.randint(floor, ceiling)\n", " while number == excluded_number:\n", " number = random.randint(floor, ceiling)\n", " return number\n", "\n", "def augment_dataframe(df, team_list, abbreviation_list, database):\n", " augmented_df = df.copy()\n", " for _, row in df.iterrows():\n", " team_idx = find_teams_in_sample(row[\"natural_query\"], team_list)\n", " # Only do simple update if only one team detected \n", " if len(team_idx) == 1:\n", " team_idx = team_idx[0]\n", "\n", " # Check if team name is used in SQL query\n", " if team_list[team_idx] in row[\"sql_query\"]:\n", " # Create updated query with new team \n", " new_team_name = team_list[get_random_excluding(0, 29, team_idx)]\n", " new_natural_query = row[\"natural_query\"].replace(team_list[team_idx], new_team_name)\n", " new_sql_query = row[\"sql_query\"].replace(team_list[team_idx], new_team_name)\n", "\n", " # Obtain result of running on sqlite database\n", " try:\n", " database.execute(new_sql_query)\n", " rows = database.fetchall()\n", " if len(rows) == 1:\n", " if len(rows[0]) == 2 and rows[0][1] == None:\n", " result = str(rows[0][0])\n", " else:\n", " result = \" | \".join(str(x) for x in rows[0]) \n", " else:\n", " result = \" | \".join(str(x) for x in rows)\n", " # Append new row to augmented dataframe if result successful\n", " new_row = pd.DataFrame([{'natural_query': new_natural_query, 'sql_query': new_sql_query, 'result': result}])\n", " augmented_df = pd.concat([augmented_df, new_row], ignore_index=True)\n", " except:\n", " pass\n", "\n", " # Check if abbreviation is in SQL query used instead\n", " elif abbreviation_list[team_idx] in row[\"sql_query\"]:\n", " # Create updated query with new team \n", " new_index = get_random_excluding(0, 29, team_idx)\n", " new_team_name = team_list[new_index]\n", " new_team_abbreviation = abbreviation_list[new_index]\n", " new_natural_query = row[\"natural_query\"].replace(team_list[team_idx], new_team_name)\n", " new_sql_query = row[\"sql_query\"].replace(abbreviation_list[team_idx], new_team_abbreviation)\n", "\n", " # Obtain result of running on sqlite database\n", " try:\n", " database.execute(new_sql_query)\n", " rows = database.fetchall()\n", " if len(rows) == 1:\n", " \n", " if len(rows[0]) == 2 and rows[0][1] == None:\n", " result = str(rows[0][0])\n", " else:\n", " result = \" | \".join(str(x) for x in rows[0]) \n", " else:\n", " result = \" | \".join(str(x) for x in rows)\n", " # Append new row to augmented dataframe if result successful\n", " new_row = pd.DataFrame([{'natural_query': new_natural_query, 'sql_query': new_sql_query, 'result': result}])\n", " augmented_df = pd.concat([augmented_df, new_row], ignore_index=True)\n", " except:\n", " pass\n", " return augmented_df\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Test functions on small dataframe sample" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Total dataset examples: 1044\n", "New Dataset Length:\n", "6\n", "\n", "What is the total free throws made by the Indiana Pacers at home?\n", "SELECT SUM(ftm_home) as total_ftm FROM game WHERE team_name_home = 'Indiana Pacers';\n", "39545.0\n", "\n", "How many total rebounds did the Los Angeles Lakers grab in the 1985 season?\n", "SELECT SUM(reb) AS total_rebounds FROM ( SELECT reb_home AS reb FROM game WHERE team_abbreviation_home = 'LAL' AND season_id = '21985' UNION ALL SELECT reb_away AS reb FROM game WHERE team_abbreviation_away = 'LAL' AND season_id = '21985' );\n", "3655.0\n", "\n", "How many home games did the Orlando Magic play in the 2013 season?\n", "SELECT COUNT(*) FROM game WHERE team_name_home = 'Orlando Magic' AND season_id = '22013';\n", "41.0\n", "\n", "What is the total free throws made by the Denver Nuggets at home?\n", "SELECT SUM(ftm_home) as total_ftm FROM game WHERE team_name_home = 'Denver Nuggets';\n", "43821.0\n", "\n", "How many total rebounds did the Miami Heat grab in the 1985 season?\n", "SELECT SUM(reb) AS total_rebounds FROM ( SELECT reb_home AS reb FROM game WHERE team_abbreviation_home = 'MIA' AND season_id = '21985' UNION ALL SELECT reb_away AS reb FROM game WHERE team_abbreviation_away = 'MIA' AND season_id = '21985' );\n", "None\n", "\n", "How many home games did the Atlanta Hawks play in the 2013 season?\n", "SELECT COUNT(*) FROM game WHERE team_name_home = 'Atlanta Hawks' AND season_id = '22013';\n", "41\n", "\n" ] } ], "source": [ "# Load dataset\n", "train_df = pd.read_csv(\"./train-data/sql_train.tsv\", sep='\\t')\n", "\n", "# Display dataset info\n", "print(f\"Total dataset examples: {len(train_df)}\")\n", "#print(train_df.head())\n", "\n", "# Setup sqlite database connection\n", "connection = sql.connect('./nba-data/nba.sqlite')\n", "cursor = connection.cursor()\n", "\n", "# Test augmentation on sample of 3 rows\n", "test_df = train_df.sample(n=3)\n", "#for _, row in test_df.iterrows():\n", " #print(row)\n", "#print()\n", "#print()\n", "\n", "# Run augmentation function and print output\n", "augmented_df = augment_dataframe(test_df, team_array, abbreviation_array, cursor)\n", "print(\"New Dataset Length:\")\n", "print(len(augmented_df))\n", "print()\n", "for _, row in augmented_df.iterrows():\n", " print(row[\"natural_query\"])\n", " print(row[\"sql_query\"])\n", " print(row[\"result\"])\n", " print()" ] } ], "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.10.9" } }, "nbformat": 4, "nbformat_minor": 2 }