You are currently looking at version 1.1 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.
All questions are weighted the same in this assignment.
The following code loads the olympics dataset (olympics.csv), which was derrived from the Wikipedia entry on All Time Olympic Games Medals, and does some basic data cleaning.
The columns are organized as # of Summer games, Summer medals, # of Winter games, Winter medals, total # number of games, total # of medals. Use this dataset to answer the questions below.
In [2]:
import pandas as pd
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
for col in df.columns:
if col[:2]=='01':
df.rename(columns={col:'Gold'+col[4:]}, inplace=True)
if col[:2]=='02':
df.rename(columns={col:'Silver'+col[4:]}, inplace=True)
if col[:2]=='03':
df.rename(columns={col:'Bronze'+col[4:]}, inplace=True)
if col[:1]=='№':
df.rename(columns={col:'#'+col[1:]}, inplace=True)
names_ids = df.index.str.split('\s\(') # split the index by '('
df.index = names_ids.str[0] # the [0] element is the country name (new index)
df['ID'] = names_ids.str[1].str[:3] # the [1] element is the abbreviation or ID (take first 3 characters from that)
df = df.drop('Totals')
In [3]:
# You should write your whole answer within the function provided. The autograder will call
# this function and compare the return value against the correct solution value
def answer_zero():
# This function returns the row for Afghanistan, which is a Series object. The assignment
# question description will tell you the general format the autograder is expecting
return df.iloc[0]
# You can examine what your function returns by calling it in the cell. If you have questions
# about the assignment formats, check out the discussion forums for any FAQs
answer_zero()
Out[3]:
In [4]:
def answer_one():
max_gold = df['Gold'].max()
ret = df[df['Gold'] == max_gold]
ans = ret.index.values
return ans[0]
print(answer_one())
In [5]:
def answer_two():
df2 = df.copy()
df2['Gold_diff'] = df['Gold'] - df['Gold.1']
score = []
for row in df2['Gold_diff']:
if row < 0:
row = row * -1
score.append(row)
else:
score.append(row)
df2['score'] = score
max_score = df2['score'].max()
name = df2[df2['score'] == max_score]
country_name = name.index.values
return country_name[0]
print(answer_two())
Which country has the biggest difference between their summer gold medal counts and winter gold medal counts relative to their total gold medal count?
$$\frac{Summer~Gold - Winter~Gold}{Total~Gold}$$Only include countries that have won at least 1 gold in both summer and winter.
This function should return a single string value.
In [6]:
def answer_three():
df2 = df.copy()
df2 = df2[(df2['Gold'] > 0) & (df2['Gold.1'] > 0)]
df2['Gold_diff'] = (df2['Gold'] - df2['Gold.1']) / df2['Gold.2']
score = []
for row in df2['Gold_diff']:
if row < 0:
row = row * -100
score.append(row)
else:
row = row * 100
score.append(row)
df2['score'] = score
df3 = df2[['Gold','Gold.1','Gold.2','score',]]
max_score = df3['score'].max()
name = df3[df3['score'] == max_score]
country_name = name.index.values
return country_name[0]
print(answer_three())
Write a function to update the dataframe to include a new column called "Points" which is a weighted value where each gold medal (Gold.2
) counts for 3 points, silver medals (Silver.2
) for 2 points, and bronze medals (Bronze.2
) for 1 point. The function should return only the column (a Series object) which you created.
This function should return a Series named Points
of length 146
In [7]:
def answer_four():
df2 = df.copy()
df2['Points'] = df2['Gold.2']*3 + df2['Silver.2']*2 + df2['Bronze.2']*1
df3 = df2[['Gold.2','Silver.2','Bronze.2','Points']]
return df3['Points']
print(answer_four())
For the next set of questions, we will be using census data from the United States Census Bureau. Counties are political and geographic subdivisions of states in the United States. This dataset contains population data for counties and states in the US from 2010 to 2015. See this document for a description of the variable names.
The census dataset (census.csv) should be loaded as census_df. Answer questions using this as appropriate.
Which state has the most counties in it? (hint: consider the sumlevel key carefully! You'll need this for future questions too...)
This function should return a single string value.
In [13]:
census_df = pd.read_csv('census.csv')
census_df
Out[13]:
In [9]:
def answer_five():
maximum_country = census_df.groupby(["STNAME"]).size().max()
g2 = census_df.groupby(["STNAME"]).size()
df3 = g2.reset_index()
name = df3[df3[0] == maximum_country]
name = name.set_index('STNAME').index.values[0]
return name
print(answer_five())
In [39]:
def answer_six():
df = census_df.copy()
df=df[df['SUMLEV'] == 50]
df = df[['CTYNAME', 'CENSUS2010POP']]
df = df.set_index('CTYNAME')
idx = df.sum(axis=1).sort_values(ascending=False).head(3).index
# df1 = df.ix[idx]
df1 = list(idx.values)
return idx
print(answer_six())
Which county has had the largest absolute change in population within the period 2010-2015? (Hint: population values are stored in columns POPESTIMATE2010 through POPESTIMATE2015, you need to consider all six columns.)
e.g. If County Population in the 5 year period is 100, 120, 80, 105, 100, 130, then its largest change in the period would be |130-80| = 50.
This function should return a single string value.
In [43]:
def answer_seven():
df = census_df.copy()
df=df[df['SUMLEV'] == 50]
df = df[['STNAME','CTYNAME','POPESTIMATE2015','POPESTIMATE2014','POPESTIMATE2013','POPESTIMATE2012','POPESTIMATE2011','POPESTIMATE2010']]
df = df.set_index(['STNAME', 'CTYNAME'])
df1 = df.apply(lambda x: x.max() - x.min(),axis=1)
df2 = df1.reset_index()
df2 = df2.sort_values([0],ascending=[0])
df3 = df2.set_index('CTYNAME').index.values
return df3[0]
print(answer_seven())
In this datafile, the United States is broken up into four regions using the "REGION" column.
Create a query that finds the counties that belong to regions 1 or 2, whose name starts with 'Washington', and whose POPESTIMATE2015 was greater than their POPESTIMATE 2014.
This function should return a 5x2 DataFrame with the columns = ['STNAME', 'CTYNAME'] and the same index ID as the census_df (sorted ascending by index).
In [34]:
def answer_eight():
df = census_df.copy()
df = df[(df['REGION'] == 1) | (df['REGION'] == 2)]
df = df[df['CTYNAME'] == 'Washington County']
df = df[df['POPESTIMATE2015'] > df['POPESTIMATE2014']]
return df[['STNAME','CTYNAME']]
print(answer_eight())
In [ ]: