# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: hackathon
#     language: python
#     name: hackathon
# ---

# +
import ruamel.yaml as yaml
import os
import sys
import pandas as pd
import numpy as np


NO_CONFIG_ERR_MSG = """No config file found. Root directory is determined by presence of "config.yaml" file."""

original_wd = os.getcwd()

# Number of times to move back in directory
num_retries = 10
for x in range(0, num_retries):
    # try to load config file
    try:
        with open("config.yaml", 'r') as stream:
            cfg = yaml.safe_load(stream)
    # If not found move back one directory level
    except FileNotFoundError:
        os.chdir('../')
        # If reached the max number of directory levels change to original wd and print error msg
        if x+1 == num_retries:
            os.chdir(original_wd)
            print(NO_CONFIG_ERR_MSG)

# Add directory to PATH
path = os.getcwd()

if path not in sys.path:
    sys.path.append(path)

# -

# ## Load Data

RPM_df = pd.read_csv('data/interim/player_RPM_stats.csv')
box_score_df = pd.read_csv('data/raw/Box_Scores.csv')

# ## Joining RPM to players
#
# Need to join on composite key made up of Player Name + Season

# season_id appears to be calendar year the season started in 
#
# Based off of the latest season being 2017 and not 2018

box_score_df['season_id'].unique()

RPM_df.head()

# most number of whitespaces 
RPM_df['names'].str.split(' ').apply(len).max()

# +
# Who has more than one space?

RPM_df['name_length_post_split'] = RPM_df['names'].str.split(' ').apply(len)
RPM_df.query("name_length_post_split > 2").names.value_counts().head()

# Mostly Jrs and some multiple names
# -

# What's the RPM of these players?

RPM_df.query("name_length_post_split > 2").RPM.describe()

first_name_to_search = 'Tim'
box_score_df[box_score_df.First_Name.str.contains(first_name_to_search)].head()

# #### For now, will join to get RPM on a season/team/player level and fix this later if necessary

potential_keys = [
    'First_Name',
    'Last_Name',
    'season_id',
]

# #### Steps:
#
# 1) RPM: Seperate names into first and last (start by splitting on a space)
#
# 2) Match season_id to either the calendar year the season ended or began. Map to RPM data
#
# 3) Join on First, Last, Season

game_mapping_df = pd.read_csv('data/raw/Game_Mapping.csv')
game_mapping_df.head()
game_mapping_df['Calendar_Year'] = game_mapping_df.Date_EST.str.split('/').str.get(-1)
calendar_year_to_df_map = game_mapping_df.groupby(by=['Calendar_Year', 'Season']).size().to_frame('count').reset_index()



team_tricodes_df = pd.read_csv('data/raw/Team_Tricodes.csv')
team_tricodes_df.head()

team_mapping = pd.read_csv('data/raw/Team_Mapping.csv')
team_mapping.head(20)

calendar_year_to_df_map

# Only use season codes that start with 2
season_codes = [season_code for season_code in calendar_year_to_df_map.Season.unique() if str(season_code).startswith('2')]
season_code_starting_year = [int(str(season_code)[1:]) for season_code in season_codes]
season_code_ending_year = [season_code+1 for season_code in season_code_starting_year]

# +
season_id_records = {
    'season_id':season_codes,
    'Season_Start_Year':season_code_starting_year,
    'Season_End_Year':season_code_ending_year,
    
}
# -

season_id_map = pd.DataFrame.from_dict(season_id_records)
season_id_map.head()

# #### Merge to RPM data and check for nulls

# +
RPM_df = pd.merge(RPM_df,
        season_id_map,
        on=['Season_Start_Year', 'Season_End_Year'],
                 how='left')

RPM_df['season_id'].isnull().sum()

# -

RPM_df.head()

# #### Split Names First and Last

RPM_df['First_Name'] = RPM_df['names'].str.split(' ').str.get(0)
RPM_df['Last_Name'] = RPM_df['names'].str.split(' ').str.get(-1)

# ## Merge onto Box score

RPM_df[potential_keys].dtypes

box_score_df[potential_keys].dtypes

# Max should be number of seasons since 2013 (when RPM was introduced)

RPM_df[potential_keys].groupby(by=['First_Name', 'Last_Name']).count().sort_values(by='season_id', ascending=False).head()

box_score_df[potential_keys]

# +
test_merge = pd.merge(RPM_df, box_score_df,
                     on=['season_id', 'First_Name', 'Last_Name'],
                     )

test_merge.head()
# -



StarcoderdataJupyterScriptsDedupFiltered