#!/usr/bin/env python # coding: utf-8 # --- # # _You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-data-analysis/resources/0dhYG) course resource._ # # --- # # Assignment 3 - More Pandas # All questions are weighted the same in this assignment. This assignment requires more individual learning then the last one did - you are encouraged to check out the [pandas documentation](http://pandas.pydata.org/pandas-docs/stable/) to find functions or methods you might not have used yet, or ask questions on [Stack Overflow](http://stackoverflow.com/) and tag them as pandas and python related. And of course, the discussion forums are open for interaction with your peers and the course staff. # ### Question 1 # Load the energy data from the file `Energy Indicators.xls`, which is a list of indicators of [energy supply and renewable electricity production](Energy%20Indicators.xls) from the [United Nations](http://unstats.un.org/unsd/environment/excel_file_tables/2013/Energy%20Indicators.xls) for the year 2013, and should be put into a DataFrame with the variable name of **energy**. # # Keep in mind that this is an Excel file, and not a comma separated values file. Also, make sure to exclude the footer and header information from the datafile. The first two columns are unneccessary, so you should get rid of them, and you should change the column labels so that the columns are: # # `['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable's]` # # Convert the energy supply and the energy supply per capita to gigajoules (there are 1,000,000 gigajoules in a petajoule). For all countries which have missing data (e.g. data with "...") make sure this is reflected as `np.NaN` values. # # Rename the following list of countries (for use in later questions): # # ```"Republic of Korea": "South Korea", # "United States of America": "United States", # "United Kingdom of Great Britain and Northern Ireland": "United Kingdom", # "China, Hong Kong Special Administrative Region": "Hong Kong"``` # # There are also several countries with parenthesis in their name. Be sure to remove these, e.g. `'Bolivia (Plurinational State of)'` should be `'Bolivia'`. # #
# # Next, load the GDP data from the file `world_bank.csv`, which is a csv containing countries' GDP from 1960 to 2015 from [World Bank](http://data.worldbank.org/indicator/NY.GDP.MKTP.CD). Call this DataFrame **GDP**. # # Make sure to skip the header, and rename the following list of countries: # # ```"Korea, Rep.": "South Korea", # "Iran, Islamic Rep.": "Iran", # "Hong Kong SAR, China": "Hong Kong"``` # #
# # Finally, load the [Sciamgo Journal and Country Rank data for Energy Engineering and Power Technology](http://www.scimagojr.com/countryrank.php?category=2102), which ranks countries based on their journal contributions in the aforementioned area. Call this DataFrame **ScimEn**. # # Join the three datasets: GDP, Energy, and ScimEn into a new dataset (using the intersection of country names). Use only the last 10 years (2006-2015) of GDP data and only the top 15 countries by Scimagojr 'Rank' (Rank 1 through 15). # # The index of this DataFrame should be the name of the country. # # *This function should return a DataFrame with 20 columns and 15 entries.* # In[ ]: import pandas as pd import numpy as np import re def get_energy(): energy = pd.read_excel('Energy Indicators.xls', skiprows=17, skipfooter=38) energy.drop(['Unnamed: 0', 'Unnamed: 2'], axis=1, inplace=True) # drop first two columns energy.columns = ['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable'] # add column names energy['Country'] = energy['Country'].apply(lambda s: re.sub(r'\s\(\w.*', '', s)) # remove parentheses energy.replace('...', np.NaN, inplace=True) # replace cells with no values dicts = {"Republic of Korea": "South Korea", "United States of America": "United States", "United Kingdom of Great Britain and Northern Ireland": "United Kingdom", "China, Hong Kong Special Administrative Region": "Hong Kong"} energy.replace({'Country':dicts}, inplace=True) energy['Energy Supply'] *= 1000000 # conversion to gigajuoles return energy def get_GDP(): GDP = pd.read_csv('world_bank.csv', skiprows=4) dicts = {"Korea, Rep.": "South Korea", "Iran, Islamic Rep.": "Iran", "Hong Kong SAR, China": "Hong Kong"} GDP = GDP.rename(columns={'Country Name' : 'Country'}) GDP['Country'] = GDP['Country'].apply(lambda s: re.sub(r',\sThe$', '', s)) # remove parentheses GDP.replace({'Country':dicts}, inplace=True) return GDP get_GDP() def get_ScimEn(): ScimEn = pd.read_excel('scimagojr-3.xlsx') return ScimEn # In[ ]: def answer_one(): energy = get_energy() GDP = get_GDP() ScimEn = get_ScimEn() #list_col = [str(x) for x in range(1960, 2006)] #gdp_10 = GDP.drop(list_col, axis=1) # drop years 1960-2005 to_keep = ['Country'] + [str(x) for x in range(2006, 2016)] gdp_10 = GDP[to_keep] sci_15 = ScimEn.drop(ScimEn.index[15:191]) # first 15 countries en_gdp = pd.merge(energy, gdp_10, how='inner', on='Country') en_gdp_sci = pd.merge(en_gdp, sci_15, how='inner', on='Country') en_gdp_sci = en_gdp_sci.set_index('Country') col_to_keep = ['Energy Supply', 'Energy Supply per Capita', '% Renewable', 'Rank', 'Documents', 'Citable documents', 'Citations', 'Self-citations', 'Citations per document', 'H index', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015'] en_gdp_sci = en_gdp_sci[col_to_keep] return en_gdp_sci.sort(columns='Rank') answer_one() # print('{:15.15}{:15.15}{:15.15}'.format( # 'dataframe', 'Starts with', 'Ends with')) # print('{:15.15}{:15.15}{:15.15}'.format( # '----------', '-----------', '---------')) # print('{:15.15}{:15.15}{:15.15}'.format('energy', get_energy() # ['Country'].iloc[0], get_energy()['Country'].iloc[-1])) # print('{:15.15}{:15.15}{:15.15}'.format('GDP', get_GDP()[ # 'Country'].iloc[0], get_GDP()['Country'].iloc[-1])) # print('{:15.15}{:15.15}{:15.15}'.format('ScimEn', get_ScimEn() # ['Country'].iloc[0], get_ScimEn()['Country'].iloc[-1])) # # In[ ]: # ### Question 2 (6.6%) # The previous question joined three datasets then reduced this to just the top 15 entries. When you joined the datasets, but before you reduced this to the top 15 items, how many entries did you lose? # # *This function should return a single number.* # In[ ]: get_ipython().run_cell_magic('HTML', '', '\n \n \n \n \n Everything but this!\n\n') # In[ ]: def answer_two(): energy = get_energy() GDP = get_GDP() ScimEn = get_ScimEn() len_energy = len(energy) len_GDP = len(GDP) len_sci = len(ScimEn) en_gdp = pd.merge(energy, GDP, how='outer', on='Country') en_gdp_sci = pd.merge(en_gdp, ScimEn, how='outer', on='Country') en_gdp2 = pd.merge(energy, GDP, how='inner', on='Country') en_gdp_sci2 = pd.merge(en_gdp, ScimEn, how='inner', on='Country') len_union = len(en_gdp_sci) len_inter = len(en_gdp_sci2) return len_union - len_inter answer_two() # In[ ]: # ### Question 3 (6.6%) # What are the top 15 countries for average GDP over the last 10 years? # # *This function should return a Series named `avgGDP` with 15 countries and their average GDP sorted in descending order.* # In[ ]: # In[ ]: def answer_three(): Top15 = answer_one() r = [str(x) for x in range(2006, 2016)] Top15['avgGDP'] = Top15[r].mean(axis=1) p = Top15['avgGDP'].copy() p.sort(ascending=False) return p #answer_three() # ### Question 4 (6.6%) # By how much had the GDP changed over the 10 year span for the country with the 6th largest average GDP? # # *This function should return a single number.* # In[ ]: def answer_four(): Top15 = answer_one() gdp2015 = Top15.loc['United Kingdom', '2015'] gdp2006 = Top15.loc['United Kingdom', '2006'] return gdp2015 - gdp2006 #answer_four() # ### Question 5 (6.6%) # What is the mean energy supply per capita? # # *This function should return a single number.* # In[ ]: # In[ ]: def answer_five(): Top15 = answer_one() mean = Top15['Energy Supply per Capita'].mean(axis=0) return mean #answer_five() # ### Question 6 (6.6%) # What country has the maximum % Renewable and what is the percentage? # # *This function should return a tuple with the name of the country and the percentage.* # In[ ]: def answer_six(): Top15 = answer_one() ren = Top15['% Renewable'].copy() ren.sort(ascending=False) return (ren.index[0], ren.loc[ren.index[0]]) #answer_six() # ### Question 7 (6.6%) # Create a new column that is the ratio of Self-Citations to Total Citations. # What is the maximum value for this new column, and what country has the highest ratio? # # *This function should return a tuple with the name of the country and the ratio.* # In[ ]: def answer_seven(): Top15 = answer_one() Top15['ratio'] = Top15['Self-citations']/Top15['Citations'] Top15 = Top15.sort(['ratio'], ascending=False) return (Top15.index[0], Top15.loc[Top15.index[0], 'ratio']) #answer_seven() # ### Question 8 (6.6%) # # Create a column that estimates the population using Energy Supply and Energy Supply per capita. # What is the third most populous country according to this estimate? # # *This function should return a single string value.* # In[ ]: def answer_eight(): Top15 = answer_one() Top15['population'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita'] Top15 = Top15.sort(['population'], ascending=False) return Top15.index[2] #answer_eight() # ### Question 9 (6.6%) # Create a column that estimates the number of citable documents per person. # What is the correlation between the number of citable documents per capita and the energy supply per capita? # # *This function should return a single number.* # # *(Optional: Use the built-in function `plot9()` to visualize the relationship between Energy Supply per Capita vs. Citable docs per Capita).* # In[ ]: def answer_nine(): Top15 = answer_one() Top15['population'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita'] Top15['cit_per_person'] = Top15['Citable documents'] / Top15['population'] return (np.correlate(Top15['cit_per_person'], Top15['Energy Supply per Capita']))#[0] #answer_nine() # In[ ]: def plot9(): import matplotlib as plt get_ipython().run_line_magic('matplotlib', 'inline') Top15 = answer_one() Top15['PopEst'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita'] Top15['Citable docs per Capita'] = Top15['Citable documents'] / Top15['PopEst'] Top15.plot(x='Citable docs per Capita', y='Energy Supply per Capita', kind='scatter', xlim=[0, 0.0006]) # In[ ]: #plot9() # ### Question 10 (6.6%) # Create a new column with a 1 if the country's % Renewable value is at or above the median for all countries in the top 15. # # *This function should return a series named `HighRenew` whose index is the country name sorted in ascending order of rank.* # In[ ]: def answer_ten(): Top15 = answer_one() med = Top15['% Renewable'].median(axis=0) Top15['HighRenew'] = 0 condition = Top15['% Renewable'] < 15 # I have to make it so that 15 and above would turn out False Top15['HighRenew'].where(condition, 1, inplace=True) p = Top15['HighRenew'].copy() p.sort(ascending = False) return p #answer_ten() # ### Question 11 (6.6%) # Use the following dictionary to group the Countries by Continent, then create a dateframe that displays the sample size (the number of countries in each continent bin), and the sum, mean, and std deviation for the estimated population of each country. # # ```python # ContinentDict = {'China':'Asia', # 'United States':'North America', # 'Japan':'Asia', # 'United Kingdom':'Europe', # 'Russian Federation':'Europe', # 'Canada':'North America', # 'Germany':'Europe', # 'India':'Asia', # 'France':'Europe', # 'South Korea':'Asia', # 'Italy':'Europe', # 'Spain':'Europe', # 'Iran':'Asia', # 'Australia':'Australia', # 'Brazil':'South America'} # ``` # # *This function should return a DataFrame with index named Continent `['Asia', 'Australia', 'Europe', 'North America', 'South America']` and columns `['size', 'sum', 'mean', 'std']`* # In[ ]: # In[ ]: def answer_eleven(): Top15 = answer_one() Top15['population'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita'] ContinentDict = {'China':'Asia', 'United States':'North America', 'Japan':'Asia', 'United Kingdom':'Europe', 'Russian Federation':'Europe', 'Canada':'North America', 'Germany':'Europe', 'India':'Asia', 'France':'Europe', 'South Korea':'Asia', 'Italy':'Europe', 'Spain':'Europe', 'Iran':'Asia', 'Australia':'Australia', 'Brazil':'South America'} for k, v in ContinentDict.items(): # add the continent column Top15.loc[k, 'Continent'] = v cols = ['Continent', 'population', 'Energy Supply', 'Energy Supply per Capita', '% Renewable', 'Rank', 'Documents', 'Citable documents', 'Citations', 'Self-citations', 'Citations per document', 'H index', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015'] Top15 = Top15[cols] Top15 = Top15.reset_index() Top15 = Top15.set_index(['Continent', 'Country']) Top15 = Top15.sort_index() p = Top15.groupby(level=0)['population'].agg({'sum' : np.sum, 'mean' : np.mean, 'std' : np.std}) p['size'] = Top15.reset_index().groupby('Continent')['Country'].nunique().astype(float) return p #answer_eleven() # ### Question 12 (6.6%) # Cut % Renewable into 5 bins. Group Top15 by the Continent, as well as these new % Renewable bins. How many countries are in each of these groups? # # *This function should return a Series with a MultiIndex of `Continent`, then the bins for `% Renewable`. Do not include groups with no countries.* # In[ ]: # In[ ]: def answer_twelve(): Top15 = answer_one() return "ANSWER" # ### Question 13 (6.6%) # Convert the Population Estimate series to a string with thousands separator (using commas) # # e.g. 12345678.90 -> 12,345,678.90 # # *This function should return a Series `PopEst` whose index is the country name and whose values are the population estimate string.* # In[ ]: # In[ ]: def answer_thirteen(): Top15 = answer_one() p = (Top15['Energy Supply'] / Top15['Energy Supply per Capita']) p = p.apply(lambda x: "{:,}".format(x)) return p #answer_thirteen() # ### Optional # # Use the built in function `plot_optional()` to see an example visualization. # In[ ]: def plot_optional(): import matplotlib as plt get_ipython().run_line_magic('matplotlib', 'inline') ax = Top15.plot(x='Rank', y='% Renewable', kind='scatter', c=['#e41a1c','#377eb8','#e41a1c','#4daf4a','#4daf4a','#377eb8','#4daf4a','#e41a1c', '#4daf4a','#e41a1c','#4daf4a','#4daf4a','#e41a1c','#dede00','#ff7f00'], xticks=range(1,16), s=6*Top15['2014']/10**10, alpha=.75, figsize=[16,6]); for i, txt in enumerate(Top15.index): ax.annotate(txt, [Top15['Rank'][i], Top15['% Renewable'][i]], ha='center') print("This is an example of a visualization that can be created to help understand the data. \ This is a bubble chart showing % Renewable vs. Rank. The size of the bubble corresponds to the countries' \ 2014 GDP, and the color corresponds to the continent.") # In[ ]: # plot_optional()