0%

Coursera | Introduction to Data Science in Python(University of Michigan)| Assignment3

   u1s1,这门课的assignment还是有点难度的,特别是assigment4(哀怨),放给大家参考啦~
   有时间(需求)就把所有代码放到github上(好担心被河蟹啊)
   相关链接:
   Coursera | Introduction to Data Science in Python(University of Michigan)| Quiz
   Coursera | Introduction to Data Science in Python(University of Michigan)| Assignment1
   Coursera | Introduction to Data Science in Python(University of Michigan)| Assignment2
   Coursera | Introduction to Data Science in Python(University of Michigan)| Assignment3
   Coursera | Introduction to Data Science in Python(University of Michigan)| Assignment4
   CSDN链接:
   Coursera | Introduction to Data Science in Python(University of Michigan)| Quiz答案
   Coursera | Introduction to Data Science in Python(University of Michigan)| Assignment1
   Coursera | Introduction to Data Science in Python(University of Michigan)| Assignment2
   Coursera | Introduction to Data Science in Python(University of Michigan)| Assignment3
   Coursera | Introduction to Data Science in Python(University of Michigan)| Assignment4

  assignment3开始难度暴增,到4就爽翻了。一共13题,刺激。

Assignment 3

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 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. All questions are worth the same number of points except question 1 which is worth 17% of the assignment grade.

Note: Questions 2-13 rely on your question 1 answer.

1
2
3
4
5
6
import pandas as pd
import numpy as np

# Filter all warnings. If you would like to see the warnings, please comment the two lines below.
import warnings
warnings.filterwarnings('ignore')

Question 1

Load the energy data from the file assets/Energy Indicators.xls, which is a list of indicators of energy supply and renewable electricity production (assets/Energy%20Indicators.xls) 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):

1
2
3
4
"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:

1
2
3
"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”.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def answer_one():
# YOUR CODE HERE
# raise NotImplementedError()
Energy = pd.read_excel('assests/Energy Indicators.xls',na_values=["..."],header = None,skiprows=18,skipfooter= 38,usecols=[2,3,4,5],names=['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable'])
Energy['Energy Supply'] = Energy['Energy Supply'].apply(lambda x: x*1000000)

Energy['Country'] = Energy['Country'].str.replace(r" \(.*\)","")
Energy['Country'] = Energy['Country'].str.replace(r"\d*","")
Energy['Country'] = 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'})

GDP = pd.read_csv('assests/world_bank.csv', skiprows = 4)
GDP['Country Name'] = GDP['Country Name'].replace({'Korea, Rep.': 'South Korea',
'Iran, Islamic Rep.': 'Iran',
'Hong Kong SAR, China' : 'Hong Kong'})

ScimEn = pd.read_excel('assests/scimagojr-3.xlsx')

merge1 = pd.merge(ScimEn,Energy,how="inner",left_on="Country",right_on="Country")
merge1 = merge1[merge1["Rank"]<=15]

GDP.rename(columns = {"Country Name":"Country"},inplace=True)
GDP = GDP.loc[:,['2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015',"Country"]]
merge2 = pd.merge(merge1,GDP,how="inner",left_on="Country",right_on="Country").set_index("Country")

return merge2
1
2
3
4
assert type(answer_one()) == pd.DataFrame, "Q1: You should return a DataFrame!"

assert answer_one().shape == (15,20), "Q1: Your DataFrame should have 20 columns and 15 entries!"

结果

RankDocumentsCitable documentsCitationsSelf-citationsCitations per documentH indexEnergy SupplyEnergy Supply per Capita% Renewable2006200720082009201020112012201320142015
Country
China11270501267675972374116834.701381.271910e+1193.019.7549103.992331e+124.559041e+124.997775e+125.459247e+126.039659e+126.612490e+127.124978e+127.672448e+128.230121e+128.797999e+12
United States296661947477922742654368.202309.083800e+10286.011.5709801.479230e+131.505540e+131.501149e+131.459484e+131.496437e+131.520402e+131.554216e+131.577367e+131.615662e+131.654857e+13
Japan33050430287223024615547.311341.898400e+10149.010.2328205.496542e+125.617036e+125.558527e+125.251308e+125.498718e+125.473738e+125.569102e+125.644659e+125.642884e+125.669563e+12
United Kingdom42094420357206091378749.841397.920000e+09124.010.6004702.419631e+122.482203e+122.470614e+122.367048e+122.403504e+122.450911e+122.479809e+122.533370e+122.605643e+122.666333e+12
Russian Federation5185341830134266124221.85573.070900e+10214.017.2886801.385793e+121.504071e+121.583004e+121.459199e+121.524917e+121.589943e+121.645876e+121.666934e+121.678709e+121.616149e+12
Canada617899176202150034093012.011491.043100e+10296.061.9454301.564469e+121.596740e+121.612713e+121.565145e+121.613406e+121.664087e+121.693133e+121.730688e+121.773486e+121.792609e+12
Germany71702716831140566274268.261261.326100e+10165.017.9015303.332891e+123.441561e+123.478809e+123.283340e+123.417298e+123.542371e+123.556724e+123.567317e+123.624386e+123.685556e+12
India81500514841128763372098.581153.319500e+1026.014.9690801.265894e+121.374865e+121.428361e+121.549483e+121.708459e+121.821872e+121.924235e+122.051982e+122.200617e+122.367206e+12
France91315312973130632286019.931141.059700e+10166.017.0202802.607840e+122.669424e+122.674637e+122.595967e+122.646995e+122.702032e+122.706968e+122.722567e+122.729632e+122.761185e+12
South Korea101198311923114675225959.571041.100700e+10221.02.2793539.410199e+119.924316e+111.020510e+121.027730e+121.094499e+121.134796e+121.160809e+121.194429e+121.234340e+121.266580e+12
Italy1110964107941118502666110.201066.530000e+09109.033.6672302.202170e+122.234627e+122.211154e+122.089938e+122.125185e+122.137439e+122.077184e+122.040871e+122.033868e+122.049316e+12
Spain12942893301233362396413.081154.923000e+09106.037.9685901.414823e+121.468146e+121.484530e+121.431475e+121.431673e+121.417355e+121.380216e+121.357139e+121.375605e+121.419821e+12
Iran138896881957470191256.46729.172000e+09119.05.7077213.895523e+114.250646e+114.289909e+114.389208e+114.677902e+114.853309e+114.532569e+114.445926e+114.639027e+11NaN
Australia1488318725907651560610.281075.386000e+09231.011.8108101.021939e+121.060340e+121.099644e+121.119654e+121.142251e+121.169431e+121.211913e+121.241484e+121.272520e+121.301251e+12
Brazil158668859660702143967.00861.214900e+1059.069.6480301.845080e+121.957118e+122.056809e+122.054215e+122.208872e+122.295245e+122.339209e+122.409740e+122.412231e+122.319423e+12

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.

1
2
3
4
5
6
7
8
%%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>
Everything but th# is!

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def answer_two():
# YOUR CODE HERE
# raise NotImplementedError()
Energy = pd.read_excel('assests/Energy Indicators.xls',na_values=["..."],header = None,skiprows=18,skipfooter= 38,usecols=[2,3,4,5],names=['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable'])
Energy['Energy Supply'] = Energy['Energy Supply'].apply(lambda x: x*1000000)

Energy['Country'] = Energy['Country'].str.replace(r" \(.*\)","")
Energy['Country'] = Energy['Country'].str.replace(r"\d*","")
Energy['Country'] = 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'})

GDP = pd.read_csv('assests/world_bank.csv', skiprows = 4)
GDP['Country Name'] = GDP['Country Name'].replace({'Korea, Rep.': 'South Korea',
'Iran, Islamic Rep.': 'Iran',
'Hong Kong SAR, China' : 'Hong Kong'})

ScimEn = pd.read_excel('assests/scimagojr-3.xlsx')

inner1 = pd.merge(ScimEn,Energy,how="inner",left_on="Country",right_on="Country")

GDP.rename(columns = {"Country Name":"Country"},inplace=True)
GDP = GDP.loc[:,['2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015',"Country"]]
inner2 = pd.merge(inner1,GDP,how="inner",left_on="Country",right_on="Country").set_index("Country")

outer1 = pd.merge(ScimEn,Energy,how="outer",left_on="Country",right_on="Country")
outer2 = pd.merge(outer1,GDP,how="outer",left_on="Country",right_on="Country").set_index("Country")

return len(outer2)-len(inner2)
1
2
assert type(answer_two()) == int, "Q2: You should return an int number!"

结果

156

Question 3

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.

Code

1
2
3
4
5
def answer_three():
# YOUR CODE HERE
# raise NotImplementedError()
info=answer_one()
return info[["2006","2007","2008","2009","2010","2011","2012","2013","2014","2015"]].apply(np.mean,axis = 1).sort_values(ascending = False)
1
assert type(answer_three()) == pd.Series, "Q3: You should return a Series!"

结果


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.

Code

1
2
3
4
5
6
7
8
9
10
11
def answer_four():
# YOUR CODE HERE
# raise NotImplementedError()
info=answer_one()
info['avgGDP']=info[["2006","2007","2008","2009","2010","2011","2012","2013","2014","2015"]].apply(np.mean,axis = 1)
info.sort_values(['avgGDP'],ascending = False,inplace=True)

# g6=info.index[5]
# info.loc[g6]["2015"]-info.loc[g6]["2006"]

return info.iloc[5]['2015']-info.iloc[5]['2006']

结果

246702696075.3999

Question 5

What is the mean energy supply per capita?

This function should return a single number.

1
2
3
4
5
6
def answer_five():
# YOUR CODE HERE
# raise NotImplementedError()
info = answer_one()
return info['Energy Supply per Capita'].mean()
# return float(info['Energy Supply per Capita'].mean())

结果

157.6

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.

Code

1
2
3
4
5
6
def answer_six():
# YOUR CODE HERE
# raise NotImplementedError()
info = answer_one()
result=info.sort_values(by='% Renewable', ascending=False).iloc[0]
return (result.name,result['% Renewable'])
1
2
3
4
assert type(answer_six()) == tuple, "Q6: You should return a tuple!"

assert type(answer_six()[0]) == str, "Q6: The first element in your result should be the name of the country!"

结果

('Brazil', 69.64803)

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.

Code

1
2
3
4
5
6
7
def answer_seven():
# YOUR CODE HERE
# raise NotImplementedError()
info = answer_one()
info['Citation ratio']=info['Self-citations']/info['Citations']
result=info.sort_values(by='Citation ratio', ascending=False).iloc[0]
return (result.name,result['Citation ratio'])
1
2
3
4
assert type(answer_seven()) == tuple, "Q7: You should return a tuple!"

assert type(answer_seven()[0]) == str, "Q7: The first element in your result should be the name of the country!"

结果

('China', 0.6893126179389422)

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

Code

1
2
3
4
5
def answer_eight():
# YOUR CODE HERE
# raise NotImplementedError()
info = answer_one()
return (info['Energy Supply']/info['Energy Supply per Capita']).sort_values(ascending=False).index[2]
1
2
assert type(answer_eight()) == str, "Q8: You should return the name of the country!"

结果

'United States'

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)

Code

1
2
3
4
5
6
7
def answer_nine():
# YOUR CODE HERE
# raise NotImplementedError()
Top15 = answer_one()
Top15['PopEst'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita']
Top15['Citable docs per Capita'] = Top15['Citable documents'] / Top15['PopEst']
return Top15['Citable docs per Capita'].corr(Top15['Energy Supply per Capita'])
1
2
3
4
5
6
7
8
def plot9():
import matplotlib as plt
%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])
1
assert answer_nine() >= -1. and answer_nine() <= 1., "Q9: A valid correlation should between -1 to 1!"

结果

0.7940010435442942


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.

Code

1
2
3
4
5
6
7
def answer_ten():
# YOUR CODE HERE
# raise NotImplementedError()
Top15 = answer_one()
Rmedian=Top15["% Renewable"].median()
Top15["HighRenew"]= Top15["% Renewable"].apply(lambda x:0 if x<Rmedian else 1 )
return Top15["HighRenew"]
1
assert type(answer_ten()) == pd.Series, "Q10: You should return a Series!"

结果


Question 11

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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']

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def answer_eleven():
# YOUR CODE HERE
# raise NotImplementedError()
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'}

Top15 = answer_one()
Top15['PopEst'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita']
Top15['Continent'] = pd.Series(ContinentDict)

return Top15.groupby('Continent')['PopEst'].agg([np.size,np.sum, np.mean, np.std])
1
2
3
4
5
6
assert type(answer_eleven()) == pd.DataFrame, "Q11: You should return a DataFrame!"

assert answer_eleven().shape[0] == 5, "Q11: Wrong row numbers!"

assert answer_eleven().shape[1] == 4, "Q11: Wrong column numbers!"

结果

sizesummeanstd
Continent
Asia5.02.898666e+095.797333e+086.790979e+08
Australia1.02.331602e+072.331602e+07NaN
Europe6.04.579297e+087.632161e+073.464767e+07
North America2.03.528552e+081.764276e+081.996696e+08
South America1.02.059153e+082.059153e+08NaN

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.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def answer_twelve():
# YOUR CODE HERE
# raise NotImplementedError()
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'}

Top15 = answer_one()
Top15['Continent'] = pd.Series(ContinentDict)
Top15['% Renewable']=pd.cut(Top15['% Renewable'],5)

return Top15.groupby(['Continent','% Renewable'])['Continent'].agg(np.size).dropna()

1
2
assert type(answer_twelve()) == pd.Series, "Q12: You should return a Series!"
assert len(answer_twelve()) == 9, "Q12: Wrong result numbers!"

结果


Question 13

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

Code

1
2
3
4
5
6
def answer_thirteen():
# YOUR CODE HERE
# raise NotImplementedError()
Top15 = answer_one()
Top15['PopEst'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita']
return Top15['PopEst'].apply('{:,}'.format)
1
2
assert type(answer_thirteen()) == pd.Series, "Q13: You should return a Series!"
assert len(answer_thirteen()) == 15, "Q13: Wrong result numbers!"

结果


Optional

Use the built in function plot_optional() to see an example visualization.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.")

结果





   大家其他还有需要的就在评论留言哦 :) 欢迎讨论分享~

------------------   The End    Thanks for reading   ------------------