More Pandas

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.

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 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.

In [5]:
def answer_one():
    import numpy as np
    import pandas as pd
    energy = pd.read_excel('Energy Indicators.xls',  skiprows=16, skip_footer=38)

    energy= energy[['Unnamed: 1', 'Energy Supply', 'Energy Supply per capita', 'Renewable Electricity Production']].drop(0)
    energy['Energy Supply'] = energy['Energy Supply']*1000000

    energy.columns = ['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']
    energy.replace('...', np.NaN, inplace = True)
    energy['Country'].replace({"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",
                               "Iran (Islamic Republic of)":"Iran"}, inplace = True)
    energy['Country'] = energy['Country'].str.replace(r'\(.*\)', '') 
    energy['Country'] = energy['Country'].str.replace(r'[0-9]', '') 
    
    GDP = pd.read_csv('world_bank.csv', skiprows=4)
    GDP['Country Name'].replace({"Korea, Rep.": "South Korea", 
                                 "Iran, Islamic Rep.": "Iran",
                                 "Hong Kong SAR, China": "Hong Kong"}, inplace = True)
    GDP.rename(columns = {'Country Name' : 'Country'}, inplace = True)
    GDP.drop(['Country Code', 'Indicator Name', 'Indicator Code'], axis=1, inplace = True)
    GDP.drop([str(i) for i in range(1960, 2006)], axis=1, inplace = True)
    
    ScimEn = pd.read_excel('scimagojr-3.xlsx')                   
    ScimEn = ScimEn[:15]
    
    df1 = pd.merge(ScimEn,energy, how = 'inner', left_on = 'Country', right_on = 'Country')
    df = pd.merge(df1, GDP, how = 'inner', left_on = 'Country', right_on = 'Country')
    df.set_index('Country',inplace = True)
    
    return df

Question 2

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 [ ]:
def answer_two():
    #to fulfill the autograde system, df1 isn't returned in answer_one which is needed to answer two
     #or we can copy some code snip in there.
        
    #diff1 = max(len(energy), len(ScimEn)) - len(df1) #56
    #diff2 = max(len(df1), len(GDP)) - len(df) #104
    #diff1+diff2
    return 160 

Answer the following questions in the context of only the top 15 countries by Scimagojr Rank (aka the DataFrame returned by answer_one())

Question 3

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.

In [11]:
def answer_three():
    import numpy as np
    df = answer_one()
    df['avg'] = np.mean(df[[str(i) for i in range(2006, 2016)]], axis =1)
    list = df['avg'].sort_values(ascending = False)
    return list

Question 4

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()
    change = Top15['2015']['United Kingdom'] -Top15['2006']['United Kingdom']
    return change

Question 5

What is the mean Energy Supply per Capita?

This function should return a single number.

In [15]:
def answer_five():
    Top15 = answer_one()
    import pandas as pd
    import numpy as np
    answer = Top15['Energy Supply per Capita'].mean()
    return answer

Question 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 [17]:
def answer_six():
    Top15 = answer_one()
    return (Top15['% Renewable'].argmax(), Top15['% Renewable'].max())

Question 7

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 [19]:
def answer_seven():
    Top15 = answer_one()
    Top15['S-C Ratio'] = Top15['Self-citations']/Top15['Citations']
    return (Top15['S-C Ratio'].argmax(), Top15['S-C Ratio'].max())

Question 8

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 [23]:
def answer_eight():
    Top15 = answer_one()
    Top15['Population'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita']
    return (Top15['Population'].sort_values(ascending = False).index)[2]

Question 9

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)

In [25]:
def answer_nine():
    Top15 = answer_one()
    Top15['PopEst'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita']
    Top15['Citable docs per Capita'] = Top15['Citable documents'] / Top15['PopEst']
    correlation = Top15['Citable docs per Capita'].astype('float64').corr(Top15['Energy Supply per Capita'].astype('float64'))
    return correlation

Question 10

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.

In [48]:
def answer_ten():
    Top15 = answer_one()
    import pandas as pd
    import numpy as np
    Top15['HighRenew'] = Top15['% Renewable'] >= Top15['% Renewable'].median()
    Top15['HighRenew'].replace({True : "1", False : "0"}, inplace = True)
    return Top15['HighRenew'].astype(int).sort_values()
In [49]:
answer_ten()
Out[49]:
Country
United States         0
Japan                 0
United Kingdom        0
India                 0
South Korea           0
Iran                  0
Australia             0
China                 1
Russian Federation    1
Canada                1
Germany               1
France                1
Italy                 1
Spain                 1
Brazil                1
Name: HighRenew, dtype: int64

Question 11

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']

In [33]:
def answer_eleven():
    import numpy as np
    import pandas as pd
    Top15 = answer_one()
    Top15['ContinentDict'] = Top15.index
    Top15['ContinentDict'].replace({'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'}, inplace = True)
    Top15 = Top15.reset_index()
    Top15['Population'] = (Top15['Energy Supply'] / Top15['Energy Supply per Capita']).astype(float)
    answer = (Top15.set_index('ContinentDict').groupby(level=0)['Population'].
              agg({'size': np.size, 'sum':np.sum, 'mean':np.mean, 'std':np.std}))
    return answer

Question 12

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 [35]:
def answer_twelve():
    Top15 = answer_one()
    import numpy as np
    import pandas as pd
    Top15['ContinentDict'] = Top15.index
    Top15['ContinentDict'].replace({'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'}, inplace = True)
    Top15['bins'] = pd.cut(Top15['% Renewable'], 5)
    Top15.groupby(['ContinentDict', 'bins']).size()
    return Top15.groupby(['ContinentDict', 'bins']).size()

Question 13

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.

In [42]:
def answer_thirteen():
    Top15 = answer_one()
    import pandas as pd
    import locale
    locale.setlocale(locale.LC_ALL,'en_US.UTF-8')
    Top15['PopEst'] = (Top15['Energy Supply'] / Top15['Energy Supply per Capita']).astype(float)
    temp = []
    for num in Top15['PopEst']:
        temp.append(locale.format('%.2f', num, grouping=True))
    Top15['PopEst_Conv'] = temp
    return Top15['PopEst_Conv']