You are currently looking at version 1.5 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 course resource.
This assignment requires more individual learning then the last one did - you are encouraged to check out the pandas documentation to find functions or methods you might not have used yet, or ask questions on Stack Overflow 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.
Load the energy data from the file Energy Indicators.xls
, which is a list of indicators of energy supply and renewable electricity production from the United Nations 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']
Convert Energy Supply
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 numbers and/or parenthesis in their name. Be sure to remove these,
e.g.
'Bolivia (Plurinational State of)'
should be 'Bolivia'
,
'Switzerland17'
should be 'Switzerland'
.
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. 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 from the file scimagojr-3.xlsx
, 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, and the columns should be ['Rank', 'Documents', 'Citable documents', 'Citations', 'Self-citations', 'Citations per document', 'H index', 'Energy Supply', 'Energy Supply per Capita', '% Renewable', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015'].
This function should return a DataFrame with 20 columns and 15 entries.
import pandas as pd
import numpy as np
def energy_clean_up() :
energy = (pd.read_excel('Energy Indicators.xls')[16:243]
.drop(['Unnamed: 0', 'Unnamed: 1'], axis = 1)
.rename(columns = {'Environmental Indicators: Energy': 'Country',
'Unnamed: 3': 'Energy Supply',
'Unnamed: 4': 'Energy Supply per Capita',
'Unnamed: 5': '% Renewable'}))
energy['Country'].replace({'Australia1': 'Australia',
'China2': 'China',
'China, Hong Kong Special Administrative Region3': 'Hong Kong',
'China, Macao Special Administrative Region4': 'China, Macao Special Administrative Region',
'Denmark5': 'Denmark',
'France6': 'France',
'Greenland7': 'Greenland',
'Indonesia8': 'Indonesia',
'Italy9': 'Italy',
'Japan10': 'Japan',
'Kuwait11': 'Kuwait',
'Netherlands12': 'Netherlands',
'Portugal13': 'Portugal',
'Saudi Arabia14': 'Saudi Arabia',
'Serbia15': 'Serbia',
'Spain16': 'Spain',
'Switzerland17': 'Switzerland',
'Ukraine18': 'Ukraine',
'United Kingdom of Great Britain and Northern Ireland19': 'United Kingdom',
'United States of America20': 'United States',
'Bolivia (Plurinational State of)': 'Bolivia',
'Falkland Islands (Malvinas)': 'Falkland Islands',
'Iran (Islamic Republic of)': 'Iran',
'Micronesia (Federated States of)': 'Micronesia',
'Sint Maarten (Dutch part)': 'Sint Maarten',
'Venezuela (Bolivarian Republic of)': 'Venezuela',
'Republic of Korea': 'South Korea'}, inplace = True)
energy.set_index('Country', inplace = True)
energy['Energy Supply'] *= 1000000
energy['Energy Supply'] = pd.to_numeric(energy['Energy Supply'], errors='coerce')
energy['Energy Supply per Capita'] = pd.to_numeric(energy['Energy Supply per Capita'], errors='coerce')
return energy
def GDP_clean_up() :
GDP = (pd.read_csv('world_bank.csv')[4:]
.rename(columns = {'Data Source': 'Country'})
.drop(['World Development Indicators'], axis = 1)
.drop(['Unnamed: '+ str(x) for x in range(2, 50)], axis = 1)
.rename(columns = {'Unnamed: ' + str(x): str(1956+x) for x in range(50,60)})
)
GDP['Country'].replace({'Korea, Rep.': 'South Korea',
'Iran, Islamic Rep.': 'Iran',
'Hong Kong SAR, China': 'Hong Kong',}, inplace = True)
GDP.set_index('Country', inplace = True)
return GDP
def ScimEn_clean_up() :
ScimEn = (pd.read_excel('scimagojr-3.xlsx'))
ScimEn.set_index('Country', inplace = True)
return ScimEn
ScimEn_clean_up()
def myjoin(dummy) :
energy = energy_clean_up()
GDP = GDP_clean_up()
ScimEn = ScimEn_clean_up()
if dummy == 'inner' :
answer = (ScimEn.merge(energy, left_index = True, right_index = True, how = 'inner')
.merge(GDP, left_index = True, right_index = True, how = 'inner'))
else :
answer = (ScimEn.merge(energy, left_index = True, right_index = True, how = 'outer')
.merge(GDP, left_index = True, right_index = True, how = 'outer'))
answer.sort('Rank', inplace = True)
return answer
def answer_one() :
return myjoin('inner').head(15)
answer_one()
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.
%%HTML
<svg width="800" height="300">
<circle cx="150" cy="180" r="80" fill-opacity="0.2" stroke="black" stroke-width="2" fill="blue" />
<circle cx="200" cy="100" r="80" fill-opacity="0.2" stroke="black" stroke-width="2" fill="red" />
<circle cx="100" cy="100" r="80" fill-opacity="0.2" stroke="black" stroke-width="2" fill="green" />
<line x1="150" y1="125" x2="300" y2="150" stroke="black" stroke-width="2" fill="black" stroke-dasharray="5,3"/>
<text x="300" y="165" font-family="Verdana" font-size="35">Everything but this!</text>
</svg>
def answer_two():
return (len(myjoin('outer')) - len(myjoin('inner')))
answer_two()
answer_one()
)¶What is the average GDP over the last 10 years for each country? (exclude missing values from this calculation.)
This function should return a Series named avgGDP
with 15 countries and their average GDP sorted in descending order.
def answer_three() :
Only_GDP = answer_one()[[str(2006+x) for x in range(0,10)]]
avgGDP = (pd.Series(Only_GDP.mean(axis = 1))).sort_values(ascending = False)
return avgGDP
answer_three()
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.
def answer_four():
Top15 = answer_one()
country = answer_three()[5:6].index.tolist()[0]
return (Top15.loc[country, '2015'] - Top15.loc[country, '2006'])
answer_four()
What is the mean Energy Supply per Capita
?
This function should return a single number.
def answer_five():
Top15 = answer_one()
return Top15['Energy Supply per Capita'].mean()
answer_five()
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.
def answer_six():
Top15 = answer_one()
max_value = Top15['% Renewable'].max()
country = Top15.index[Top15['% Renewable'] == max_value].tolist()[0]
return (country, max_value)
answer_six()
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.
def answer_seven():
Top15 = answer_one()
Top15['Citation Ratio'] = Top15['Self-citations'] / Top15['Citations']
max_value = Top15['Citation Ratio'].max()
country = Top15.index[Top15['Citation Ratio'] == max_value].tolist()[0]
return (country, max_value)
answer_seven()
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.
def answer_eight():
Top15 = answer_one()
Top15['Population Estimate'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita']
return Top15['Population Estimate'].sort_values(ascending = False)[2:3].index.tolist()[0]
answer_eight()
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? Use the .corr()
method, (Pearson's correlation).
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)
def answer_nine():
Top15 = answer_one()
Top15['Population Estimate'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita']
Top15['Citable docs per Capita'] = Top15['Citable documents'] / Top15['Population Estimate']
ToCorrelate = Top15[['Citable docs per Capita', 'Energy Supply per Capita']]
return ToCorrelate.corr(method='pearson')['Citable docs per Capita'].tolist()[1]
answer_nine()
def plot9():
import matplotlib as plt
Top15 = answer_one()
Top15['Population Estimate'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita']
Top15['Citable docs per Capita'] = Top15['Citable documents'] / Top15['Population Estimate']
%matplotlib inline
Top15.plot(x='Citable docs per Capita', y='Energy Supply per Capita', kind='scatter', xlim=[0, 0.0006])
plot9()
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, and a 0 if the country's % Renewable value is below the median.
This function should return a series named HighRenew
whose index is the country name sorted in ascending order of rank.
def answer_ten():
Top15 = answer_one()
median_value = Top15['% Renewable'].median()
Top15['HighRenew'] = (Top15['% Renewable'] >= median_value).astype(int)
return Top15['HighRenew']
answer_ten()
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.
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']
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'}
def answer_eleven():
Top15 = answer_one()
Top15['Population Estimate'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita']
Continent_Data = pd.DataFrame(data = 0,
index = ['Asia', 'Australia', 'Europe', 'North America', 'South America'],
columns = ['size', 'sum', 'mean', 'std'])
Continents = Continent_Data.index.tolist()
PopulationDict = {x: [] for x in Continents}
for Continent in Continents :
for Country in ContinentDict :
if ContinentDict[Country] == Continent :
Continent_Data.loc[Continent, 'size'] += 1
temp_pop = Top15.loc[Country, 'Population Estimate']
Continent_Data.loc[Continent, 'sum'] += temp_pop
PopulationDict[Continent].append(temp_pop)
Continent_Data['mean'] = Continent_Data['sum'] / Continent_Data['size']
for Continent in Continents :
Continent_Data.loc[Continent, 'std'] = np.std(PopulationDict[Continent])
return Continent_Data
answer_eleven()
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.
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'}
def answer_twelve():
Top15 = answer_one()
Top15['Continent'] = pd.Series({x: ContinentDict[x] for x in Top15.index})
Top15['% Renewable'] = pd.cut(Top15['% Renewable'], 5)
temp = ((Top15.reset_index())
.pivot_table(index = ['Continent', '% Renewable'],
values = 'Country',
aggfunc = 'count')
.fillna(0)
.astype(int))
return temp[temp != 0]
answer_twelve()
Convert the Population Estimate series to a string with thousands separator (using commas). Do not round the results.
e.g. 317615384.61538464 -> 317,615,384.61538464
This function should return a Series PopEst
whose index is the country name and whose values are the population estimate string.
#By the way, this worked for me. But grader gave me 0/100
#import locale
#locale.setlocale(locale.LC_ALL, 'en_US.utf8')
#def answer_thirteen():
# Top15 = answer_one()
# Top15['PopEst'] = ((Top15['Energy Supply'] / Top15['Energy Supply per Capita'])
# .apply(lambda x: locale.format("%.8f", x, grouping=True))
# .astype(str))
# return Top15['PopEst']
#answer_thirteen()
def convert(num) :
num_str = str(num)
dec_loc = num_str.find('.')
dec = num_str[dec_loc:]
hun = num_str[(dec_loc-3):dec_loc]
tho = num_str[(dec_loc-6):(dec_loc-3)]
mil = num_str[:(dec_loc-6)]
new_format = (tho + ',' + hun + dec)
if int(mil) >= 1000 :
return mil[0] + ',' + mil[1:4] + ',' + new_format
else :
return mil + ',' + new_format
def answer_thirteen():
Top15 = answer_one()
Top15['PopEst'] = ((Top15['Energy Supply'] / Top15['Energy Supply per Capita']))
Top15['PopEst'] = Top15['PopEst'].map(lambda x: convert(x))
return (Top15['PopEst'])
answer_thirteen()
Use the built in function plot_optional()
to see an example visualization.
def plot_optional():
import matplotlib as plt
%matplotlib inline
Top15 = answer_one()
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.")
plot_optional()