Week 2
Assignment 2 – Pandas Introduction
All questions are weighted the same in this assignment.
Part 1
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.
import pandas as pd
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
# print(df)
print('---------------')
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 = df.drop('Totals')
# print(df.head)
def answer_one():
return df.iloc[0]
print (answer_one())
Question 0 (Example)
What is the first country in df?
This function should return a Series.
# 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()
Question 1
Which country has won the most gold medals in summer games?
This function should return a single string value.
import pandas as pd
def answer_one():
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 = df.drop('Totals')
return max(df.idxmax())
answer_one()
Question 2
Which country had the biggest difference between their summer and winter gold medal counts?
This function should return a single string value.
import pandas as pd
def answer_two():
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 = df.drop('Totals')
df['diff'] = (df['Gold'] - df['Gold.1'])
difference = (df['diff'].max())
return (df['diff'].idxmax())
answer_two()
Question 3
Which country has the biggest difference between their summer gold medal counts and winter gold medal counts relative to their total gold medal count?
Only include countries that have won at least 1 gold in both summer and winter.
This function should return a single string value.
import pandas as pd
def answer_three():
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 = df.drop('Totals')
df = df.where(df['Gold'] > 0)
df['rel'] = ((df['Gold'] - df['Gold.1'])/df['Gold.1'])
(df['rel'].max())
return (df['rel'].idxmax())
answer_three()
Question 4
Write a function to update the dataframe to include a new column called “Points” which is a weighted value where each gold medal counts for 3 points, silver medals for 2 points, and bronze mdeals 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
def answer_four():
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
df = df.drop('Totals')
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['Points'] = ((df['Gold']*3) + (df['Silver']*2) + (df['Bronze.1']) + (df['Gold.1']*3) + (df['Silver.1']*2) + (df['Bronze.1']))
df['Points'] = (df['Gold.2']*3) + (df['Silver.2']*2) + (df['Bronze.2'])
# print((df['Gold']*3).head())
# print(df.head())
# print(df['Points'])
# print(len(df['Points']))
# print(type(df['Points']))
return ((df['Points']))
answer_four()
Part 2
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.
Question 5
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.
import pandas as pd
census_df = pd.read_csv('census.csv')
census_df.head()
import pandas as pd
def answer_five():
df = pd.read_csv('census.csv')
df=df[df['SUMLEV'] == 50]
columns_to_keep = ['STNAME',
'CTYNAME',
'BIRTHS2010',
'BIRTHS2011',
'BIRTHS2012',
'BIRTHS2013',
'BIRTHS2014',
'BIRTHS2015',
'POPESTIMATE2010',
'POPESTIMATE2011',
'POPESTIMATE2012',
'POPESTIMATE2013',
'POPESTIMATE2014',
'POPESTIMATE2015']
df = df[columns_to_keep]
maxx = df.groupby('STNAME')['CTYNAME'].nunique().idxmax()
return maxx
answer_five()
Question 6
Only looking at the three most populous counties for each state, what are the three most populous states (in order of highest population to lowest population)?
This function should return a list of string values.
import pandas as pd
def answer_six():
df = pd.read_csv('census.csv')
df=df[df['SUMLEV'] == 50]
columns_to_keep = ['STNAME',
'CTYNAME',
'CENSUS2010POP']
df = df[columns_to_keep]
df = (df.groupby('STNAME')['CENSUS2010POP'].apply(lambda x: x.nlargest(3).sum()).nlargest(3).index.values.tolist())
return df
Question 7
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 it’s largest change in the period would be |130-80| = 50.
This function should return a single string value.
import pandas as pd
def answer_seven():
df = pd.read_csv('census.csv')
df=df[df['SUMLEV'] == 50]
columns_to_keep = ['CTYNAME',
'POPESTIMATE2010',
'POPESTIMATE2011',
'POPESTIMATE2012',
'POPESTIMATE2013',
'POPESTIMATE2014',
'POPESTIMATE2015']
df = df[columns_to_keep]
df = df.set_index('CTYNAME')
df['min'] = (df.min(axis=1, skipna=True))
# print((df['min']).head())
df['max'] = (df.max(axis=1, skipna=True))
# print((df['max']).head())
# print("---------------------------------")
df['diff'] = df['max'] - df['min']
cty = ((df['diff']).idxmax())
# print(type(cty))
return cty
answer_seven()
Question 8
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 5×2 DataFrame with the columns = [‘STNAME’, ‘CTYNAME’] and the same index ID as the census_df (sorted ascending by index).
import pandas as pd
import numpy as np
def answer_eight():
df = pd.read_csv('census.csv')
df=df[df['SUMLEV'] == 50]
df=df[(df['REGION'] == 1) | (df['REGION'] == 2)]
columns_to_keep = ['STNAME',
'CTYNAME',
'POPESTIMATE2014',
'POPESTIMATE2015',
'REGION']
df = df[columns_to_keep]
df=df[(df['REGION'] == 1) | (df['REGION'] == 2)]
df=df[(df['CTYNAME']).str.startswith('Washington')]
df['max'] = np.where((df['POPESTIMATE2014'] > df['POPESTIMATE2015']), df['POPESTIMATE2014'], np.nan)
df['min'] = np.where((df['POPESTIMATE2014'] < df['POPESTIMATE2015']), df['POPESTIMATE2015'], np.nan)
# df['max']=np.where((df['POPESTIMATE2014']) > (df['POPESTIMATE2015']))
# conditions = [(df['one'] >= df['two']) & (df['one'] <= df['three']), df['one'] < df['two']]
df =df[df['min'] > 0]
columns_to_keep = ['STNAME',
'CTYNAME']
df = df[columns_to_keep]
# print (df)
# print (type(df))
return df
answer_eight()
Leave a comment