<file_sep># <NAME> - Data Analytics for Business - Final Project (Project Rubric) - Script 2 Charts & Presentation

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns


# File import and treatment section
# Assign filename: file
file = 'output.csv'

# Import file: data
medals = pd.read_csv(file, sep=',', na_values=['Nothing'])
print(medals['Year'].unique())
print(medals['Country'].unique())
print(medals.columns)
print(medals.isnull().sum())



# File review and summary section
# Display sample data of the DataFrame
print(medals.head(5))

# Display max medals count by country
print("Max amount of gold medals by one country at any one Olympic games: " + str((medals["Gold"].max())))
print("Max amount of silver medals by one country at any one Olympic games: " + str((medals["Silver"].max())))
print("Max amount of bronze medals by one country at any one Olympic games: " + str((medals["Bronze"].max())))

#Display countries with the most Gold medals
top_10_countries_by_year = medals.groupby('Country')['Gold'].sum().sort_values(ascending=False).head(10)
print(top_10_countries_by_year)

yearly_view = (medals.pivot_table (index = "Country", columns="Year",values=['Gold'], fill_value=0))
print(yearly_view)

# Display Gold medal wins by reference to the relative wealth of countries
medals.groupby(["GDP_Strata", "Gold"]).sum()
wealthiest_countries = (medals.pivot_table (index = "Country", columns="GDP_Strata",values=['Gold'], fill_value="0"))
print(wealthiest_countries)

# Display Gold Medal wins by reference to the most populous countries
medals.groupby(["Population_Strata", "Gold"]).sum()
populous_countries = (medals.pivot_table (index = "Country", columns="Population_Strata",values=['Gold'], fill_value="0"))
print(populous_countries)



#Display Charts section
# List top performing countries by ref to gold medals
top_countries = ['USA', 'URS', 'GBR', 'CHN', 'JPN'] # Note Japan only entered top 4 only when Olympics were in Japan 2020
team_medals = pd.pivot_table(medals,index = 'Year',columns = 'Country',values = 'Gold',aggfunc = 'sum')[top_countries]
team_medals.plot(linestyle = '-', marker = 's', linewidth = 3)
plt.xlabel('Olympic Year')
plt.ylabel('Number of Medals')
plt.title('Top Countries - Olympic Performance Comparison')
plt.grid()
plt.show()

#Display medal wins against population level of the countries
plt.figure
sns.catplot(x='Population_Strata',kind='count',data=medals, order=medals.Population_Strata.value_counts().index)
plt.title('Gold Medal wins versus population level',fontsize=16)
plt.grid()
plt.show()


#Display medal wins against relative wealth level of the countries
plt.figure
sns.catplot(x='GDP_Strata',kind='count',data=medals, order=medals.GDP_Strata.value_counts().index)
plt.title('Gold Medal wins versus GDP per capita',fontsize=12)
plt.grid()
plt.show()


medals.groupby('GDP_Strata')[['Gold','Bronze','Silver']].sum().plot.bar(color=['gold','red','grey'])
plt.xlabel('Country',fontsize=12)
plt.ylabel('Medal Count',fontsize=12)
plt.title('All Countries All medals by GDP per capita',fontsize=14)
plt.grid()
plt.show()


# Focus on Ireland performance
# Display ALL Irish medal wins
medals[medals['Country']=='IRL'][['Gold','Bronze','Silver']].sum().plot.bar(color=['gold','red','grey'])
plt.xlabel('IRELAND OLYMPIC MEDALS TOTAL',fontsize=10)
plt.ylabel('TOTAL MEDALS',fontsize=10)
plt.title('Total Irish Olympic Medal Wins',fontsize=14)
plt.grid()
plt.show()

# Display ALL Irish medal wins
ireland_results = medals[medals['Country']=='IRL'].sort_values(['Year'], ascending=True)
print (ireland_results)
sns.barplot(y='Gold', x='Year' , data=ireland_results.sort_values(['Gold']),color="green")
plt.xlabel('Ireland performance by year',fontsize=10)
plt.ylabel('Year',fontsize=10)
plt.title('All Irish Gold Medal Wins by year',fontsize=14)
plt.grid()
plt.show()


# Focus on USA performance at 1904 and 1984 games
USA_results = medals[medals['Country']=='USA'].sort_values(['Year'], ascending=True)
print (USA_results)
sns.barplot(y='Gold', x='Year' , data=USA_results.sort_values(['Gold']),color="blue")
plt.xlabel('USA performance by year',fontsize=10)
plt.ylabel('Year',fontsize=10)
plt.title('All USA Gold Medal Wins by year',fontsize=14)
plt.grid()
plt.show()


# Focus on China performance since 1984
# Display ALL Chinese medal wins
china_results = medals[medals['Country']=='CHN'].sort_values(['Year'], ascending=True)
print (china_results)
sns.barplot(y='Gold', x='Year' , data=china_results.sort_values(['Gold']),color="red")
plt.xlabel('China performance by year',fontsize=10)
plt.ylabel('Year',fontsize=10)
plt.title('All Chinese Gold Medal Wins since 1984',fontsize=14)
plt.grid()
plt.show()

<file_sep># <NAME> - Data Analytics for Business - Final Project (Project Rubric) - Script 1


import csv
import pandas as pd
import numpy as np


# import olympic medals base data
def get_medals_dict():
    with open('Country_Medals_New.csv', mode='r') as infile:
        next(infile)  # skip header
        reader = csv.reader(infile)
        # key is Country_Code & Year as integer value with each of medal count. Return True where country is host
        return {tuple([rows[1][1:-1], int(rows[0])]): [rows[5], rows[6], rows[7], rows[2] == rows[4]] for rows in
                reader}


# identify all Olympic years
olympic_year_list = ['1952', '1956', '1960', '1964', '1968', '1972', '1976', '1980', '1984', '1988', '1992', '1996', '2000', '2004', '2008', '2012',
                     '2016', '2020']


# extract a GDP figure for the nearest Olympic year
def get_gdp_dict():
    with open('gdp.csv', mode='r') as infile: #
        next(infile) #skip header
        reader = csv.reader(infile)
        gdp_dict = {}
        for rows in reader:
            year = get_closest_olympic_year(rows[5])
            gdp_dict[tuple([rows[0], year])] = (int(rows[6]))
            if rows[0] is not None and rows[6] is not None:
                gdp_dict[tuple([rows[0], int(rows[5])])] = (int(rows[6]))
        return gdp_dict


# Extract a Population figure for the nearest Olympic year
def get_pop_dict():
    with open('pop.csv', mode='r') as infile: #
        next(infile) #skip header
        reader = csv.reader(infile)
        pop_dict = {}
        for rows in reader:
            year = get_closest_olympic_year(rows[5])
            pop_dict[tuple([rows[0], year])] = (int(rows[6]))
            if rows[0] is not None and rows[6] is not None:
                pop_dict[tuple([rows[0], int(rows[5])])] = (int(rows[6]))
        return pop_dict


# apply reusable logic to matching up olympic years, subject to defined olympic year list
def get_closest_olympic_year(year):
    count = 0
    while count + 1 < len(olympic_year_list) and year >= olympic_year_list[count + 1]:
        count += 1
    return olympic_year_list[count]


# write results in useful format to an output .CSV file
def write_results(output_dict):
    with open('mycsvfile.csv', 'w') as f:
        w = csv.DictWriter(f, output_dict.keys())
        #w.writeheader()
        #w.writerow(output_dict)
    dataframe = pd.DataFrame(output_dict)
    dataframe.transpose().to_csv('output.csv')


#def merge_dictionaries(d1, d2):
    #for key, value in d1.items():
        #if key in d2:
            #value.extend(d2[key])
        #else:
            #value.extend([None])
    #return d1


def run():
    gdp = get_gdp_dict()
    pop = get_pop_dict()
    merged_dictionaries = (gdp, pop)
    #merged_dictionaries = merge_dictionaries(gdp, pop)

    medals = get_medals_dict()
    for key, value in medals.items():
        if key[0] in merged_dictionaries:
            if len(key[0]) == 3:
                value.extend(merged_dictionaries[key[0]])
            else:
                print(key[0])
        else:
            value.extend(['Monkey', 'Bananas'])
            #value.extend(merged_dictionaries[key[0]] if key[0] in merged_dictionaries else [None, None]) #add population and gdp

    #print(merged_dictionaries)
    #print(medals)
    write_results(medals)

run()

print("Processing Completed")



