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.
License: GPL3
Examples and Exercises from Think Stats, 2nd Edition
Copyright 2016 Allen B. Downey
MIT License: https://opensource.org/licenses/MIT
Examples from Chapter 1
Read NSFG data into a Pandas DataFrame.
Print the column names.
Select a single column name.
Select a column and check what type it is.
Print a column.
Select a single element from a column.
Select a slice from a column.
Select a column using dot notation.
Count the number of times each value occurs.
Check the values of another variable.
Make a dictionary that maps from each respondent's caseid to a list of indices into the pregnancy DataFrame. Use it to select the pregnancy outcomes for a single respondent.
Exercises
Select the birthord column, print the value counts, and compare to results published in the codebook
We can also use isnull to count the number of nans.
Select the prglngth column, print the value counts, and compare to results published in the codebook
To compute the mean of a column, you can invoke the mean method on a Series. For example, here is the mean birthweight in pounds:
Create a new column named totalwgt_kg that contains birth weight in kilograms. Compute its mean. Remember that when you create a new column, you have to use dictionary syntax, not dot notation.
nsfg.py also provides ReadFemResp, which reads the female respondents file and returns a DataFrame:
DataFrame provides a method head that displays the first five rows:
Select the age_r column from resp and print the value counts. How old are the youngest and oldest respondents?
We can use the caseid to match up rows from resp and preg. For example, we can select the row from resp for caseid 2298 like this:
And we can get the corresponding rows from preg like this:
How old is the respondent with caseid 1?
What are the pregnancy lengths for the respondent with caseid 2298?
What was the birthweight of the first baby born to the respondent with caseid 5012?