[DS practice | Coursera] Assignment3 | Introduction to Data Science in Python

Posted by rwoods on Mon, 24 Jan 2022 18:01:14 +0100

preface

This chapter is the third Assignment of Introduction to Data Science in Python. The main task of this chapter is to select the appropriate method of summarizing and merging data tables based on the three tables given and on the understanding of various merging processes, that is, row data summary, clean and merge the data, and cluster the data by using the function of DataFrame, Calculate and view the statistical description value, find the maximum and minimum items and other data processing, which requires skilled use of various technologies.


1, Q1

1.1 problem description
Load the energy data from the file assets/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 (Note: 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 assets/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 assets/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, and the rows of the DataFrame should be sorted by "Rank".


1.2 problem analysis
The first question mainly introduces the data contents of three data sets, namely:

  1. Energy: the data is taken from 'energy indicators' Xls', energy index, the task takes the fields ['Country', 'Energy Supply', 'Energy Supply per capital', 'Renewable'].
  2. GDP: data from 'world'_ bank. CSV ', this task takes the GDP of the top 10 countries from 2006 to 2015.
  3. ScimEn: the data is taken from 'scimagojr-3 Xlsx ', ranking them mainly according to the journal contributions of countries in the above fields, and taking all fields.

Next, standardize the data of each data set, normalize the names in the Energy and GDP tables, for example, change "Republic of Korea" to "South Korea", remove the () and [] comments in the country names in the Energy table, convert the units of 'Energy Supply', change the column names of Energy and GDP, and finally merge the three tables together.


1.3 code and detailed explanation

#Set the function to change the name
def change_country_values(item):
    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",
            
            "Korea, Rep.": "South Korea", 
            "Iran, Islamic Rep.": "Iran",
            "Hong Kong SAR, China": "Hong Kong"}
    #Using the iterator of dicts for matching
    for key,values in dicts.items():
        if item==key:
            return values
    return item
            
def answer_one():
    #Create Energy's DataFrame
    Energy=pd.read_excel('assets/Energy Indicators.xls',skiprows=16,usecols=[2,3,4,5])
    Energy=Energy[1:228]
    
    #Change column name
    Energy.columns=['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']
    #Remove the tail patch
    Energy.replace(to_replace=' \(.*\)$',value='',regex=True,inplace=True)
    Energy.replace(to_replace='[\d]+$',value='',regex=True,inplace=True)
    Energy.replace(to_replace='^[\.]+$',value=np.nan,regex=True,inplace=True)
    #Change unit
    Energy['Energy Supply']=Energy['Energy Supply'].apply(lambda x:x*1000000)
    #Change country name
    Energy['Country']=Energy['Country'].apply(change_country_values)
    #print(Energy)
    
    #Create DataFrame for GDP
    GDP=pd.read_csv('assets/world_bank.csv',skiprows=4)
    GDP['Country Name']=GDP['Country Name'].apply(change_country_values)
    GDP.rename(columns={'Country Name':'Country'},inplace=True)
    #print(GDP.head())
    
    #Create ScimEn's DataFrame
    ScimEn=pd.read_excel('assets/scimagojr-3.xlsx')
    #print(ScimEn)
    
    #Summarize the data columns to go into a list
    year=list(range(2006,2016))
    GDP_year=[str(i) for i in year]
    GDP_year.append('Country')
    
    #Take out the data from 2006 to 2015
    GDP=GDP.loc[:,GDP_year]
    #print(GDP_year)
    
    #Merge DataFrame by country name
    merge1=pd.merge(Energy,GDP,left_on='Country',right_on='Country',how='inner')
    #print(merge1.columns)
    
    #Merge DataFrame by country name
    merge2=pd.merge(ScimEn,merge1,on='Country',how='inner')
    #print(len(merge2))
    
    #Take the top 15 after merger
    merge2=merge2[merge2['Rank']<16]
    
    #Set index
    merge2.set_index('Country',inplace=True)
    #print(merge2.columns)
    
    #Returns the merged DataFrame
    return merge2
answer_one()
  • Get the merged DataFrame
CountryRankDocumentsCitable documentsCitationsSelf-citationsCitations per documentH indexEnergy SupplyEnergy Supply per Capita% Renewable2006200720082009201020112012201320142015
China11270501267675972374116834.701381.271910e+119319.754913.992331e+124.559041e+124.997775e+125.459247e+126.039659e+126.612490e+127.124978e+127.672448e+128.230121e+128.797999e+12
United States296661947477922742654368.202309.083800e+1028611.570981.479230e+131.505540e+131.501149e+131.459484e+131.496437e+131.520402e+131.554216e+131.577367e+131.615662e+131.654857e+13
Japan33050430287223024615547.311341.898400e+1014910.232825.496542e+125.617036e+125.558527e+125.251308e+125.498718e+125.473738e+125.569102e+125.644659e+125.642884e+125.669563e+12
United Kingdom42094420357206091378749.841397.920000e+0912410.600472.419631e+122.482203e+122.470614e+122.367048e+122.403504e+122.450911e+122.479809e+122.533370e+122.605643e+122.666333e+12
Russian Federation5185341830134266124221.85573.070900e+1021417.288681.385793e+121.504071e+121.583004e+121.459199e+121.524917e+121.589943e+121.645876e+121.666934e+121.678709e+121.616149e+12
Canada617899176202150034093012.011491.043100e+1029661.945431.564469e+121.596740e+121.612713e+121.565145e+121.613406e+121.664087e+121.693133e+121.730688e+121.773486e+121.792609e+12
Germany71702716831140566274268.261261.326100e+1016517.901533.332891e+123.441561e+123.478809e+123.283340e+123.417298e+123.542371e+123.556724e+123.567317e+123.624386e+123.685556e+12
India81500514841128763372098.581153.319500e+102614.969081.265894e+121.374865e+121.428361e+121.549483e+121.708459e+121.821872e+121.924235e+122.051982e+122.200617e+122.367206e+12
France91315312973130632286019.931141.059700e+1016617.020282.607840e+122.669424e+122.674637e+122.595967e+122.646995e+122.702032e+122.706968e+122.722567e+122.729632e+122.761185e+12
South Korea101198311923114675225959.571041.100700e+102212.2793539.410199e+119.924316e+111.020510e+121.027730e+121.094499e+121.134796e+121.160809e+121.194429e+121.234340e+121.266580e+12
Italy1110964107941118502666110.201066.530000e+0910933.667232.202170e+122.234627e+122.211154e+122.089938e+122.125185e+122.137439e+122.077184e+122.040871e+122.033868e+122.049316e+12
Spain12942893301233362396413.081154.923000e+0910637.968591.414823e+121.468146e+121.484530e+121.431475e+121.431673e+121.417355e+121.380216e+121.357139e+121.375605e+121.419821e+12
Iran138896881957470191256.46729.172000e+091195.7077213.895523e+114.250646e+114.289909e+114.389208e+114.677902e+114.853309e+114.532569e+114.445926e+114.639027e+11NaN
Australia1488318725907651560610.281075.386000e+0923111.810811.021939e+121.060340e+121.099644e+121.119654e+121.142251e+121.169431e+121.211913e+121.241484e+121.272520e+121.301251e+12
Brazil158668859660702143967.00861.214900e+105969.648031.845080e+121.957118e+122.056809e+122.054215e+122.208872e+122.295245e+122.339209e+122.409740e+122.412231e+122.319423e+12

2, Q2

2.1 problem description

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.


2.2 problem analysis

Some key fields only exist in one of the two tables. During internal connection, this field will not be connected and will be deleted; When making external connections, these fields will be retained. If there is no other table, NaN will be returned. In order to see how many rows of data have been deleted, just make external connections for all three tables and subtract the number of lists of internal connections. The code body is similar to the previous question.


2.3 code and detailed explanation

def answer_two():
    Energy=pd.read_excel('assets/Energy Indicators.xls',skiprows=16,usecols=[2,3,4,5])
    Energy=Energy[1:228]
    Energy.columns=['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']
    Energy.replace(to_replace=' \(.*\)$',value='',regex=True,inplace=True)
    Energy.replace(to_replace='[\d]+$',value='',regex=True,inplace=True)
    Energy.replace(to_replace='^[\.]+$',value=np.nan,regex=True,inplace=True)
    Energy['Energy Supply']=Energy['Energy Supply'].apply(lambda x:x*1000000)
    Energy['Country']=Energy['Country'].apply(change_country_values)
    #print(Energy)
    
    GDP=pd.read_csv('assets/world_bank.csv',skiprows=4)
    GDP['Country Name']=GDP['Country Name'].apply(change_country_values)
    GDP.rename(columns={'Country Name':'Country'},inplace=True)
    #print(GDP.head())
    
    ScimEn=pd.read_excel('assets/scimagojr-3.xlsx')
    #print(ScimEn)
    
    year=list(range(2006,2016))
    GDP_year=[str(i) for i in year]
    GDP_year.append('Country')
    GDP=GDP.loc[:,GDP_year]
    #print(GDP_year)
    
    merge1=pd.merge(Energy,GDP,left_on='Country',right_on='Country',how='inner')
    #print(len(merge1))
    
    #Three intra table connections
    merge2=pd.merge(ScimEn,merge1,on='Country',how='inner')
    #print(len(merge2))

    merge3=pd.merge(Energy,GDP,left_on='Country',right_on='Country',how='outer')
    #print(len(merge3))
    
    #Three off sheet connections
    merge4=pd.merge(ScimEn,merge3,on='Country',how='outer')
    #print(len(merge4))
    ans=len(merge4)-len(merge2)
    #print(ans)
    #print(merge2.columns)
    return ans
answer_two()

The result is 158


3, Q3

3.1 problem description

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.


3.2 problem analysis

Calculate the average value of 10 years. Use the apply() function to calculate the average value of the data of each year using the anonymous function.
In descending order, sort in DataFrame can be used_ Values() function.


3.3 code

def answer_three():
    df=answer_one()
    year=list(range(2006,2015))
    year=[str(i) for i in year]
    df['avgGDP']=df[year].apply(lambda x: np.nanmean(x),axis=1)
    df=df.sort_values(ascending=False,by='avgGDP')
    return df['avgGDP']
answer_three()
Country
United States1.523276e+13
China6.076454e+12
Japan5.528057e+12
Germany3.471633e+12
France2.672896e+12
United Kingdom2.468081e+12
Brazil2.175391e+12
Italy2.128048e+12
India1.702863e+12
Canada1.645985e+12
Russian Federation1.559827e+12
Spain1.417885e+12
Australia1.148797e+12
South Korea1.088952e+12
Iran4.441558e+11

4, Q4

4.1 problem description

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.


4.2 problem analysis

How much has the sixth largest GDP economy changed in 10 years?


4.3 code

def answer_four():
    df=answer_one()
    year=list(range(2006,2015))
    year=[str(i) for i in year]
    df['avgGDP']=df[year].apply(lambda x: np.nanmean(x),axis=1)
    df=df.sort_values(ascending=False,by='avgGDP')
    return df.iloc[5]['2015']-df.iloc[5]['2006']
answer_four()  
246702696075.3999

5, Q5

5.1 problem description

What is the mean energy supply per capita?

This function should return a single number.


5.2 problem analysis

What is the average per capita energy supply?


5.3 codes

def answer_five():
    df=answer_one()
    return df['Energy Supply per Capita'].mean()
answer_five()
157.6

6, Q6

6.1 problem description

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.


6.2 problem analysis

Which country has the largest 'Renewable' value? What is the maximum value?
Here, I first convert the data in DataFrame into float, and then use the data in Series idmax() found the country where the maximum value is located


6.3 code

def answer_six():
    df=answer_one()
    return (df['% Renewable'].astype(float).idxmax(),df['% Renewable'].astype(float).max())
answer_six()
('Brazil', 69.65)

7, Q7

7.1 problem description

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.


7.2 problem analysis

Use the self quotation amount / total quotation amount to obtain the quotation ratio, and find the country with the largest data and the largest value. The method is the same as that in the previous question


7.3 codes

def answer_seven():  
    df=answer_one()
    df['ratio']=df['Self-citations']/df['Citations']
    return (df['ratio'].idxmax(),df['ratio'].max())
answer_seven()
('China', 0.69)

8, Q8

8.1 problem description

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 the name of the country


8.2 problem analysis

To estimate the population, you can use 'Energy Supply' / 'Energy Supply per capita'. The population can be obtained by dividing the total data by the per capita. The third largest can be arranged in descending order, and then the third data can be obtained


8.3 code

def answer_eight():
    df=answer_one()
    df['population']=df['Energy Supply']/df['Energy Supply per Capita']
    df.sort_values(by='population',ascending=False,inplace=True)
    return df.iloc[2].name
answer_eight()
'United States'

9, Q9

9.1 problem description

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)


9.2 problem analysis

The calculation of Pearson correlation coefficient is relatively simple. The code for choosing questions has been given, and the image can be obtained by running


9.3 code

def answer_nine():
    df=answer_one()
    df['population']=df['Energy Supply']/df['Energy Supply per Capita']
    df['citable documents per capita']=df['Citable documents']/df['population']
    return df['citable documents per capita'].astype(float).corr(df['Energy Supply per Capita'].astype(float))
answer_nine()
0.7940010435442946

10, Q10

10.1 problem description

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.


10.2 problem analysis

Find the median. If it is greater than or equal to the median, it returns 1, otherwise it returns 0


10.3 codes

def answer_ten():
    df=answer_one()
    df['flagRenew']= df['% Renewable']-df['% Renewable'].median() 
    df['HighRenew']= df['flagRenew'].apply(lambda x:1 if x>=0 else 0)
    return df['HighRenew']
answer_ten()
country
China1
United States0
Japan0
United Kingdom0
Russian Federation1
Canada1
Germany1
India0
France1
South Korea0
Italy1
Spain1
Iran0
Australia0
Brazil1

11, Q11

11.1 problem description

Use the following dictionary to group the Countries by Continent, then create a DataFrame 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']


11.2 problem analysis

Add the region information for each country, and calculate the size, sum, average and standard deviation according to the region. You can use the aggregation function, and the syntax is visible Merging, grouping and aggregation of DataFrame and PivotTable report (Chapter III grouping and aggregation)


11.3 codes

def region(row):
    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'}
    #print(row.name)
    for key,values in ContinentDict.items():
        if row.name == key:
            row['region']=values
    return row
def answer_eleven():
    df=answer_one()
    df['population']=df['Energy Supply']/df['Energy Supply per Capita']
    df=df.apply(region,axis=1)
    new_df=df.groupby('region',axis=0).agg({'population':(np.size,np.nansum,np.nanmean,np.nanstd)})
    #new_df['size']=df.groupby('region',axis=0).size()
    new_df.columns=['size','sum','mean','std']
    #print(new_df)
    return new_df
answer_eleven()


12, Q12

12.1 problem description

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.


12.2 problem analysis

Divide the '% Renewable' into 5 boxes and calculate the size of each box. You can use PD Cut () to divide the box, and the calculated size is similar to the previous question


12.3 code

def region(row):
    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'}
    #print(row.name)
    for key,values in ContinentDict.items():
        if row.name == key:
            row['Continent']=values
    return row

def answer_twelve():
    df=answer_one()
    df=df.apply(region,axis=1)
    df['% Renewable']=pd.cut(df['% Renewable'],5)
    new_df=df.groupby(['Continent','% Renewable'])['Continent'].agg(np.size).dropna()
    #new_df=new_df.set_index(['Continent','intervals'])
    return new_df

answer_twelve()


13, Q13

13.1 problem description

Convert the Population Estimate series to a string with thousands separator (using commas). Use all significant digits (do not round the results).

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


13.2 problem analysis

Change data format


13.3 code

def answer_thirteen():
    df=answer_one()
    df['population']=df['Energy Supply']/df['Energy Supply per Capita']
    return df['population'].apply('{:,}'.format)
answer_thirteen()
country
China1,367,645,161.2903225
United States317,615,384.61538464
Japan127,409,395.97315437
United Kingdom63,870,967.741935484
Russian Federation143,500,000.0
Canada35,239,864.86486486
Germany80,369,696.96969697
India1,276,730,769.2307692
France63,837,349.39759036
South Korea49,805,429.864253394
Italy59,908,256.880733944
Spain46,443,396.2264151
Iran77,075,630.25210084
Australia23,316,017.316017315
Brazil205,915,254.23728815

Topics: Python Data Analysis coursera