{ "metadata": { "name": "", "signature": "sha256:151b229e81776daa0c324f9570f662a65d79d63f75a582b79118008267af5725" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Homework 2: More Exploratory Data Analysis\n", "## Gene Expression Data and Election Polls \n", "\n", "Due: Thursday, October 2, 2014 11:59 PM\n", "\n", " Download this assignment\n", "\n", "#### Submission Instructions\n", "To submit your homework, create a folder named lastname_firstinitial_hw# and place your IPython notebooks, data files, and any other files in this folder. Your IPython Notebooks should be completely executed with the results visible in the notebook. We should not have to run any code. Compress the folder (please use .zip compression) and submit to the CS109 dropbox in the appropriate folder. If we cannot access your work because these directions are not followed correctly, we will not grade your work.\n", "\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Introduction\n", "\n", "John Tukey wrote in [Exploratory Data Analysis, 1977](http://www.amazon.com/Exploratory-Data-Analysis-Wilder-Tukey/dp/0201076160/ref=pd_bbs_sr_2/103-4466654-5303007?ie=UTF8&s=books&qid=1189739816&sr=8-2): \"The greatest value of a picture is when it forces us to notice what we never expected to see.\" In this assignment we will continue using our exploratory data analysis tools, but apply it to new sets of data: [gene expression](http://en.wikipedia.org/wiki/Gene_expression) and polls from the [2012 Presidental Election](http://en.wikipedia.org/wiki/United_States_presidential_election,_2012) and from the [2014 Senate Midterm Elections](http://en.wikipedia.org/wiki/United_States_Senate_elections,_2014). \n", "\n", "**First**: You will use exploratory data analysis and apply the [singular value decomposition](http://en.wikipedia.org/wiki/Singular_value_decomposition) (SVD) to a gene expression data matrix to determine if the the date that the gene expression samples are processed has large effect on the variability seen in the data. \n", "\n", "**Second**: You will use the polls from the 2012 Presidential Elections to determine (1) Is there a pollster bias in presidential election polls? and (2) Is the average of polls better than just one poll?\n", "\n", "**Finally**: You will use the [HuffPost Pollster API](http://elections.huffingtonpost.com/pollster/api) to extract the polls for the current 2014 Senate Midterm Elections and provide a preliminary prediction of the result of each state.\n", "\n", "#### Data\n", "\n", "We will use the following data sets: \n", "\n", "1. A gene expression data set called `exprs_GSE5859.csv` and sample annotation table called `sampleinfo_GSE5859.csv` which are both available on Github in the 2014_data repository: [expression data set](https://github.com/cs109/2014_data/blob/master/exprs_GSE5859.csv) and [sample annotation table](https://github.com/cs109/2014_data/blob/master/sampleinfo_GSE5859.csv). \n", "\n", "2. Polls from the [2012 Presidential Election: Barack Obama vs Mitt Romney](http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama). The polls we will use are from the [Huffington Post Pollster](http://elections.huffingtonpost.com/pollster). \n", "\n", "3. Polls from the [2014 Senate Midterm Elections](http://elections.huffingtonpost.com/pollster) from the [HuffPost Pollster API](http://elections.huffingtonpost.com/pollster/api). \n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load Python modules" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# special IPython command to prepare the notebook for matplotlib\n", "%matplotlib inline \n", "\n", "import requests \n", "from StringIO import StringIO\n", "import numpy as np\n", "import pandas as pd # pandas\n", "import matplotlib.pyplot as plt # module for plotting \n", "import datetime as dt # module for manipulating dates and times\n", "import numpy.linalg as lin # module for performing linear algebra operations" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Problem 1\n", "\n", "In this problem we will be using a [gene expression](http://en.wikipedia.org/wiki/Gene_expression) data set obtained from a [microarray](http://en.wikipedia.org/wiki/DNA_microarray) experiement [Read more about the specific experiment here](http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE5859). There are two data sets we will use: \n", "\n", "1. The gene expression intensities where the rows represent the features on the microarray (e.g. genes) and the columsns represent the different microarray samples. \n", "\n", "2. A table that contains the information about each of the samples (columns in the gene expression data set) such as the sex, the age, the treatment status, the date the samples were processed. Each row represents one sample. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 1(a) \n", "Read in the two files from Github: [exprs_GSE5859.csv](https://github.com/cs109/2014_data/blob/master/exprs_GSE5859.csv) and [sampleinfo_GSE5859.csv](https://github.com/cs109/2014_data/blob/master/sampleinfo_GSE5859.csv) as pandas DataFrames called `exprs` and `sampleinfo`. Use the gene names as the index of the `exprs` DataFrame." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Make sure the order of the columns in the gene expression DataFrame match the order of file names in the sample annotation DataFrame. If the order of the columns the `exprs` DataFrame do not match the order of the file names in the `sampleinfo` DataFrame, reorder the columns in the `exprs` DataFrame. \n", "\n", "**Note**: The column names of the gene expression DataFrame are the filenames of the orignal files from which these data were obtained. \n", "\n", "**Hint**: The method `list.index(x)` [[read here](https://docs.python.org/2/tutorial/datastructures.html)] can be used to return the index in the list of the first item whose value is x. It is an error if there is no such item. To check if the order of the columns in `exprs` matches the order of the rows in `sampleinfo`, you can check using the method `.all()` on a Boolean or list of Booleans: \n", "\n", "Example code: `(exprs.columns == sampleinfo.filename).all()`" ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Show the head of the two tables: `exprs` and `sampleinfo`. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 1(b)\n", "\n", "Extract the year and month as integers from the `sampleinfo` table. \n", "\n", "**Hint**: To convert a Series or a column of a pandas DataFrame that contains a date-like object, you can use the `to_datetime` function [[read here](http://pandas.pydata.org/pandas-docs/stable/timeseries.html)]. This will create a `DatetimeIndex` which can be used to extract the month and year for each row in the DataFrame. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 1(c)\n", "\n", "Convert the dates in the `date` column from the `sampleinfo` table into days since October 31, 2002. Add a column to the `sampleinfo` DataFrame titled `elapsedInDays` containing the days since October 31, 2002. Show the head of the `sampleinfo` DataFrame which includes the new column. \n", "\n", "**Hint**: Use the `datetime` module to create a new `datetime` object for the specific date October 31, 2002. Then, subtract the October 31, 2002 date from each date from the `date` column in the `sampleinfo` DataFrame. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 1(d)\n", "\n", "Use exploratory analysis and the singular value decomposition (SVD) of the gene expression data matrix to determine if the date the samples were processed has large effect on the variability seen in the data or if it is just ethnicity (which is confounded with date). \n", "\n", "**Hint**: See the end of the [lecture from 9/23/2014 for help with SVD](http://nbviewer.ipython.org/github/cs109/2014/blob/master/lectures/lecture07/data_scraping_transcript.ipynb). \n", "\n", "First subset the the `sampleinfo` DataFrame to include only the CEU ethnicity. Call this new subsetted DataFrame `sampleinfoCEU`. Show the head of `sampleinfoCEU` DataFrame. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Next, subset the `exprs` DataFrame to only include the samples with the CEU ethnicity. Name this new subsetted DataFrame `exprsCEU`. Show the head of the `exprsCEU` DataFrame. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Check to make sure the order of the columns in the `exprsCEU` DataFrame matches the rows in the `sampleinfoCEU` DataFrame. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Compute the average gene expression intensity in the `exprsCEU` DataFrame across all the samples. For each sample in the `exprsCEU` DataFrame, subtract the average gene expression intensity from each of the samples. Show the head of the mean normalized gene expression data. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 9 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using this mean normalized gene expression data, compute the projection to the first Principal Component (PC1). \n", "\n", "**Hint**: Use the `numpy.linalg.svd()` function in the `numpy.linalg` module (or the `scipy.linalg.svd()` function in the `scipy.linalg` module) to apply an [singular value decomposition](http://en.wikipedia.org/wiki/Singular_value_decomposition) to a matrix. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 10 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Create a histogram using the values from PC1. Use a bin size of 25. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Create a scatter plot with the days since October 31, 2002 on the x-axis and PC1 on the y-axis." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 12 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Around what day do you notice a difference in the way the samples were processed?" ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 13 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Discussion for Problem 1\n", "\n", "*Write a brief discussion of your conclusions to the questions and tasks above in 100 words or less.*\n", "\n", "---\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Problem 2: Is there a pollster bias in presidential election polls?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 2(a)\n", "\n", "The [HuffPost Pollster](http://elections.huffingtonpost.com/pollster) contains many political polls. You can access these polls from individual races as a CSV but you can also access polls through the [HuffPost Pollster API](http://elections.huffingtonpost.com/pollster/api) to access the data. \n", "\n", "Read in the polls from the [2012 Presidential Election: Barack Obama vs Mitt Romney](http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama) into a pandas DataFrame called `election`. For this problem, you may read in the polls for this race directly using [the CSV file](http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama.csv) available from the HuffPost Pollster page." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 14 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Show the head of the `election` DataFrame. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 15 }, { "cell_type": "markdown", "metadata": {}, "source": [ "How many polls were conducted in November? Define this number as M. \n", "\n", "**Hint**: Subset the `election` DataFrame for only dates in the `Start Date` column that are in November 2012. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 16 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What was the median of the number of observations in the November polls? Define this quantity as N. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 17 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 2(b)\n", "\n", "Using the median sample size $N$ from Problem 1(a), simulate the results from a single poll: simulate the number of votes for Obama out of a sample size $N$ where $p$ = 0.53 is the percent of voters who are voting for Obama. \n", "\n", "**Hint**: Use the binomial distribution with parameters $N$ and $p$ = 0.53. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 18 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, perform a Monte Carlo simulation to obtain the estimated percentage of Obama votes with a sample size $N$ where $N$ is the median sample size calculated in Problem 2(a). Let $p$=0.53 be the percent of voters are voting for Obama. \n", "\n", "**Hint**: You will repeat the simulation above 1,000 times and plot the distribution of the estimated *percent* of Obama votes from a single poll. The results from the single poll you simulate is random variable and will be different every time you sample. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 19 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plot the distribution of the estimated percentage of Obama votes from your single poll. What is the distribution of the estimated percentage of Obama votes? " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 20 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What is the standard error (SE) of the estimated percentage from the poll. \n", "\n", "**Hint**: Remember the SE is the standard deviation (SD) of the distribution of a random variable. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 21 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 2(c)\n", "\n", "Now suppose we run M polls where M is the number of polls that happened in November (calculated in Problem 2(a)). Run 1,000 simulations and compute the mean of the M polls for each simulation. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 22 }, { "cell_type": "markdown", "metadata": {}, "source": [ "What is the distribution of the average of polls?\n", "\n", "**Hint**: Show a plot. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 23 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What is the standard error (SE) of the average of polls? " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 24 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Is the SE of the average of polls larger, the same, or smaller than that the SD of a single poll (calculated in Problem 2(b))? By how much?\n", "\n", "**Hint**: Compute a ratio of the two quantities. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 25 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 2(d) \n", "\n", "Repeat Problem 2(c) but now record the *across poll* standard deviation in each simulation. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 26 }, { "cell_type": "markdown", "metadata": {}, "source": [ "What is the distribution of the *across M polls* standard deviation?\n", "\n", "**Hint**: Show a plot. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 27 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 2(e) \n", "\n", "What is the standard deviation of M polls in our real (not simulated) 2012 presidential election data ? " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 28 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Is this larger, the same, or smaller than what we expeced if polls were not biased." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 29 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 2(f)\n", "\n", "**For AC209 Students**: Learn about the normal approximation for the binomial distribution and derive the results of Problem 2(b) and 2(c) analytically (using this approximation). Compare the results obtained analytically to those obtained from simulations." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 30 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Discussion for Problem 2\n", "\n", "*Write a brief discussion of your conclusions to the questions and tasks above in 100 words or less.*\n", "\n", "---\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Problem 3: Is the average of polls better than just one poll?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 3(a)\n", "\n", "Most undecided voters vote for one of the two candidates at the election. Therefore, the reported percentages underestimate the final value of both candidates. However, if we assume the undecided will split evenly, then the observed difference should be an unbiased estimate of the final difference. \n", "\n", "Add a new column to the `election` DataFrame containg the difference between Obama and Romeny called `Diff`. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 31 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 3(b)\n", "\n", "Make a plot of the differences for the week before the election (e.g. 5 days) where the days are on the x-axis and the differences are on the y-axis. Add a horizontal line showing 3.9%: the difference between Obama and Romney on election day." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 32 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 3(c) \n", "\n", "Make a plot showing the differences by pollster where the pollsters are on the x-axis and the differences on the y-axis. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 33 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Is the *across poll* difference larger than the *between pollster* difference? " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 3(d)\n", "\n", "Take the average for each pollster and then compute the average of that. Given this difference how confident would you have been of an Obama victory?\n", "\n", "**Hint**: Compute an estimate of the SE of this average based exclusively on the observed data. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 34 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 3(e)\n", "\n", "**For AC209 Students**: Show the difference against time and see if you can detect a trend towards the end. Use this trend to see if it improves the final estimate." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 35 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Answer: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Discussion for Problem 3\n", "\n", "*Write a brief discussion of your conclusions to the questions and tasks above in 100 words or less.*\n", "\n", "---\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Problem 4\n", "\n", "In this last problem, we will use the polls from the [2014 Senate Midterm Elections](http://elections.huffingtonpost.com/pollster) from the [HuffPost Pollster API](http://elections.huffingtonpost.com/pollster/api) to create a preliminary prediction of the result of each state. \n", "\n", "The HuffPost Pollster API allows you to access the data as a CSV or a JSON response by tacking \".csv\" or \".json\" at the end of the URLs. For example the 2012 Presidential Election could be accessed as a [.json](http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama.json) instead of a [.csv](http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama.csv)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 4(a)\n", "\n", "Read in the polls for **all** of the 2014 Senate Elections using the HuffPost API. For example, we can consider the [2014 Senate race in Kentucky between Mitch McConnell and Alison Grimes](http://elections.huffingtonpost.com/pollster/2014-kentucky-senate-mcconnell-vs-grimes). \n", "\n", "To search for the 2014 Senate races, use the `topics` parameter in the API [[read more about topics here](http://elections.huffingtonpost.com/pollster/api)]. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "url_str = \"http://elections.huffingtonpost.com/pollster/api/charts/?topic=2014-senate\"" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 36 }, { "cell_type": "markdown", "metadata": {}, "source": [ "To list all the URLs related to the 2014 Senate races using the pollster API, we can use a list comprehension:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "election_urls = [election['url'] + '.csv' for election in requests.get(url_str).json()]\n", "election_urls" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 37, "text": [ "[u'http://elections.huffingtonpost.com/pollster/2014-kentucky-senate-mcconnell-vs-grimes.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-arkansas-senate-cotton-vs-pryor.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-michigan-senate-land-vs-peters.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-louisiana-senate-cassidy-vs-landrieu.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-new-hampshire-senate-brown-vs-shaheen.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-west-virginia-senate-capito-vs-tennant.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-new-hampshire-senate-bass-vs-shaheen.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-north-carolina-senate-tillis-vs-hagan.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-virginia-senate-gillespie-vs-warner.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-colorado-senate-gardner-vs-udall.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-illinois-senate-oberweis-vs-durbin.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-alaska-senate-sullivan-vs-begich.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-iowa-senate-ernst-vs-braley.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-mississippi-senate-cochran-vs-childers.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-oregon-senate-wehby-vs-merkley.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-georgia-senate-perdue-vs-nunn.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-louisiana-senate-sasse-vs-domina.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-south-dakota-senate-rounds-vs-weiland.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-maine-senate-collins-vs-bellows.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-minnesota-senate-mcfadden-vs-franken.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-texas-senate-cornyn-vs-alameel.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-south-carolina-senate-graham-vs-hutto.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-south-carolina-senate-scott-vs-dickerson.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-oklahoma-senate-inhofe-vs-silverstein.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-new-mexico-senate-weh-vs-udall.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-new-jersey-senate-bell-vs-booker.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-idaho-senate-risch-vs-mitchell.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-tennessee-senate-alexander-vs-ball.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-wyoming-senate.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-kansas-senate-roberts-vs-orman-vs-taylor.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-hawaii-senate-cavasso-vs-schatz.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-oklahoma-senate-lankford-vs-johnson.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-montana-senate-daines-vs-curtis.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-rhode-island-senate-zaccaria-vs-reed.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-massachusetts-senate-herr-vs-markey.csv',\n", " u'http://elections.huffingtonpost.com/pollster/2014-delaware-senate-wade-vs-coons.csv']" ] } ], "prompt_number": 37 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Because there so many Senate races, we can create a dictionary of pandas DataFrames that will be keyed by the name of the election (a string). " ] }, { "cell_type": "code", "collapsed": false, "input": [ "def build_frame(url):\n", " \"\"\"\n", " Returns a pandas DataFrame object containing\n", " the data returned from the given url\n", " \"\"\"\n", " source = requests.get(url).text\n", " \n", " # Use StringIO because pd.DataFrame.from_csv requires .read() method\n", " s = StringIO(source)\n", " \n", " return pd.DataFrame.from_csv(s, index_col=None).convert_objects(\n", " convert_dates=\"coerce\", convert_numeric=True)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 38 }, { "cell_type": "code", "collapsed": false, "input": [ "# Makes a dictionary of pandas DataFrames keyed on election string.\n", "dfs = dict((election.split(\"/\")[-1][:-4], build_frame(election)) for election in election_urls)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 39 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Show the head of the DataFrame containing the polls for the 2014 Senate race in Kentucky between McConnell and Grimes." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 40 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Problem 4(b)\n", "\n", "For each 2014 Senate race, create a preliminary prediction of the result for that state." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#your code here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 42 }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Submission Instructions\n", "\n", "To submit your homework, create a folder named **lastname_firstinitial_hw#** and place your IPython notebooks, data files, and any other files in this folder. Your IPython Notebooks should be completely executed with the results visible in the notebook. We should not have to run any code. Compress the folder (please use .zip compression) and submit to the CS109 dropbox in the appropriate folder. *If we cannot access your work because these directions are not followed correctly, we will not grade your work.*\n" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }