Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

Think Stats by Allen B. Downey Think Stats is an introduction to Probability and Statistics for Python programmers.

This is the accompanying code for this book.

Website: http://greenteapress.com/wp/think-stats-2e/

Views: 7115
License: GPL3
Kernel: Python 3

Examples and Exercises from Think Stats, 2nd Edition

http://thinkstats2.com

Copyright 2016 Allen B. Downey

MIT License: https://opensource.org/licenses/MIT

from __future__ import print_function, division %matplotlib inline import numpy as np import nsfg import first

Given a list of values, there are several ways to count the frequency of each value.

t = [1, 2, 2, 3, 5]

You can use a Python dictionary:

hist = {} for x in t: hist[x] = hist.get(x, 0) + 1 hist
{1: 1, 2: 2, 3: 1, 5: 1}

You can use a Counter (which is a dictionary with additional methods):

from collections import Counter counter = Counter(t) counter
Counter({1: 1, 2: 2, 3: 1, 5: 1})

Or you can use the Hist object provided by thinkstats2:

import thinkstats2 hist = thinkstats2.Hist([1, 2, 2, 3, 5]) hist
Hist({1: 1, 2: 2, 3: 1, 5: 1})

Hist provides Freq, which looks up the frequency of a value.

hist.Freq(2)
2

You can also use the bracket operator, which does the same thing.

hist[2]
2

If the value does not appear, it has frequency 0.

hist[4]
0

The Values method returns the values:

hist.Values()
dict_keys([1, 2, 3, 5])

So you can iterate the values and their frequencies like this:

for val in sorted(hist.Values()): print(val, hist[val])
1 1 2 2 3 1 5 1

Or you can use the Items method:

for val, freq in hist.Items(): print(val, freq)
1 1 2 2 3 1 5 1

thinkplot is a wrapper for matplotlib that provides functions that work with the objects in thinkstats2.

For example Hist plots the values and their frequencies as a bar graph.

Config takes parameters that label the x and y axes, among other things.

import thinkplot thinkplot.Hist(hist) thinkplot.Config(xlabel='value', ylabel='frequency')
Image in a Jupyter notebook

As an example, I'll replicate some of the figures from the book.

First, I'll load the data from the pregnancy file and select the records for live births.

preg = nsfg.ReadFemPreg() live = preg[preg.outcome == 1]

Here's the histogram of birth weights in pounds. Notice that Hist works with anything iterable, including a Pandas Series. The label attribute appears in the legend when you plot the Hist.

hist = thinkstats2.Hist(live.birthwgt_lb, label='birthwgt_lb') thinkplot.Hist(hist) thinkplot.Config(xlabel='Birth weight (pounds)', ylabel='Count')
Image in a Jupyter notebook

Before plotting the ages, I'll apply floor to round down:

ages = np.floor(live.agepreg)
hist = thinkstats2.Hist(ages, label='agepreg') thinkplot.Hist(hist) thinkplot.Config(xlabel='years', ylabel='Count')
Image in a Jupyter notebook

As an exercise, plot the histogram of pregnancy lengths (column prglngth).

# Solution goes here

Hist provides smallest, which select the lowest values and their frequencies.

for weeks, freq in hist.Smallest(10): print(weeks, freq)
10.0 2 11.0 1 12.0 1 13.0 14 14.0 43 15.0 128 16.0 242 17.0 398 18.0 546 19.0 559

Use Largest to display the longest pregnancy lengths.

# Solution goes here

From live births, we can select first babies and others using birthord, then compute histograms of pregnancy length for the two groups.

firsts = live[live.birthord == 1] others = live[live.birthord != 1] first_hist = thinkstats2.Hist(firsts.prglngth, label='first') other_hist = thinkstats2.Hist(others.prglngth, label='other')

We can use width and align to plot two histograms side-by-side.

width = 0.45 thinkplot.PrePlot(2) thinkplot.Hist(first_hist, align='right', width=width) thinkplot.Hist(other_hist, align='left', width=width) thinkplot.Config(xlabel='weeks', ylabel='Count', xlim=[27, 46])
Image in a Jupyter notebook

Series provides methods to compute summary statistics:

mean = live.prglngth.mean() var = live.prglngth.var() std = live.prglngth.std()

Here are the mean and standard deviation:

mean, std
(38.56055968517709, 2.702343810070587)

As an exercise, confirm that std is the square root of var:

# Solution goes here

Here's are the mean pregnancy lengths for first babies and others:

firsts.prglngth.mean(), others.prglngth.mean()
(38.60095173351461, 38.52291446673706)

And here's the difference (in weeks):

firsts.prglngth.mean() - others.prglngth.mean()
0.07803726677754952

This functon computes the Cohen effect size, which is the difference in means expressed in number of standard deviations:

def CohenEffectSize(group1, group2): """Computes Cohen's effect size for two groups. group1: Series or DataFrame group2: Series or DataFrame returns: float if the arguments are Series; Series if the arguments are DataFrames """ diff = group1.mean() - group2.mean() var1 = group1.var() var2 = group2.var() n1, n2 = len(group1), len(group2) pooled_var = (n1 * var1 + n2 * var2) / (n1 + n2) d = diff / np.sqrt(pooled_var) return d

Compute the Cohen effect size for the difference in pregnancy length for first babies and others.

# Solution goes here

Exercises

Using the variable totalwgt_lb, investigate whether first babies are lighter or heavier than others.

Compute Cohen’s effect size to quantify the difference between the groups. How does it compare to the difference in pregnancy length?

# Solution goes here
# Solution goes here

For the next few exercises, we'll load the respondent file:

resp = nsfg.ReadFemResp()

Make a histogram of totincr the total income for the respondent's family. To interpret the codes see the codebook.

# Solution goes here

Make a histogram of age_r, the respondent's age at the time of interview.

# Solution goes here

Make a histogram of numfmhh, the number of people in the respondent's household.

# Solution goes here

Make a histogram of parity, the number of children borne by the respondent. How would you describe this distribution?

# Solution goes here

Use Hist.Largest to find the largest values of parity.

# Solution goes here

Let's investigate whether people with higher income have higher parity. Keep in mind that in this study, we are observing different people at different times during their lives, so this data is not the best choice for answering this question. But for now let's take it at face value.

Use totincr to select the respondents with the highest income (level 14). Plot the histogram of parity for just the high income respondents.

# Solution goes here

Find the largest parities for high income respondents.

# Solution goes here

Compare the mean parity for high income respondents and others.

# Solution goes here

Compute the Cohen effect size for this difference. How does it compare with the difference in pregnancy length for first babies and others?

# Solution goes here