{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# DataFrames and Series" ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "[Click here to run this notebook on Colab](https://colab.research.google.com/github/AllenDowney/ElementsOfDataScience/blob/master/07_dataframes.ipynb) or\n", "[click here to download it](https://github.com/AllenDowney/ElementsOfDataScience/raw/master/07_dataframes.ipynb)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This chapter introduces Pandas, a Python library that provides functions for reading and writing data files, exploring and analyzing data, and generating visualizations. And it provides two new types for working with data, `DataFrame` and `Series`.\n", "\n", "We will use these tools to answer a data question: what is the average birth weight of babies in the United States?\n", "This example will demonstrate important steps in almost any data science project:\n", "\n", "1. Identifying data that can answer a question.\n", "\n", "2. Obtaining the data and loading it in Python.\n", "\n", "3. Checking the data and dealing with errors.\n", "\n", "4. Selecting relevant subsets from the data.\n", "\n", "5. Using histograms to visualize a distribution of values.\n", "\n", "6. Using summary statistics to describe the data in a way that best answers the question.\n", "\n", "7. Considering possible sources of error and limitations in our conclusions.\n", "\n", "Let's start by getting the data." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reading the Data\n", "\n", "We'll use data from the National Survey of Family Growth (NSFG), which is available from the National Center for Health Statistics at .\n", "\n", "To download the data, you have to agree to the Data User's Agreement at .\n", "You should read those terms carefully, but let me draw your attention to what I think is the most important one:\n", "\n", "> Make no attempt to learn the identity of any person or establishment included in these data.\n", "\n", "NSFG respondents provide honest answers to questions of the most personal nature with the expectation that their identities will not be revealed.\n", "As ethical data scientists, we should respect their privacy and adhere to the terms of use." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Respondents to the NSFG provide general information about themselves, which is stored in the respondent file, and information about each time they have been pregnant, which is stored in the pregnancy file.\n", "\n", "We will work with the pregnancy file, which contains one row for each pregnancy and one column for each of the 248 variables.\n", "Each variable represents responses to a question on the NSFG questionnaire." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The data is stored in a fixed-width format, which means that every row is the same length and each variable spans a fixed range of characters (see ). For example, the first six characters in each row represent a variable called `CASEID`, which is a unique identifier for each respondent; the next two characters represent `PREGORDR`, which indicates whether a pregnancy is the respondent's first, second, etc.\n", "\n", "To read this data, we need a **data dictionary**, which specifies the names of the variables and the range of characters where each variable appears. The data and the data dictionary are available in separate files." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "dict_file = '2015_2017_FemPregSetup.dct'\n", "data_file = '2015_2017_FemPregData.dat'" ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "Once you have agreed to the terms, you can use the following cells to download the data." ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "tags": [] }, "outputs": [], "source": [ "from os.path import basename, exists\n", "\n", "def download(url):\n", " filename = basename(url)\n", " if not exists(filename):\n", " from urllib.request import urlretrieve\n", " local, _ = urlretrieve(url, filename)\n", " print('Downloaded ' + local)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "tags": [] }, "outputs": [], "source": [ "download('https://ftp.cdc.gov/pub/health_statistics/nchs/' +\n", " 'datasets/NSFG/stata/' + dict_file)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "tags": [] }, "outputs": [], "source": [ "download('https://ftp.cdc.gov/pub/health_statistics/nchs/' +\n", " 'datasets/NSFG/' + data_file)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Pandas can read data in most common formats, including CSV, Excel, and fixed-width format, but it cannot read the data dictionary, which is in Stata format.\n", "For that, we'll use a Python library called `statadict`." ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "The following cell installs `statadict` if necessary." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "tags": [] }, "outputs": [], "source": [ "try:\n", " from statadict import parse_stata_dict\n", "except ImportError:\n", " !pip install statadict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "From `statadict`, we'll import `parse_stata_dict`, which reads the data dictionary." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "from statadict import parse_stata_dict\n", "\n", "stata_dict = parse_stata_dict(dict_file)\n", "stata_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result is an object that contains\n", "\n", "* `names`, which is a list of variable names, and\n", "\n", "* `colspecs`, which is a list of tuples.\n", "\n", "Each tuple in `colspecs` specifies the first and last column where a variable appears.\n", "\n", "These values are exactly the arguments we need to use `read_fwf`, which is the Pandas function that reads a file in fixed-width format." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "\n", "nsfg = pd.read_fwf(data_file, \n", " names=stata_dict.names, \n", " colspecs=stata_dict.colspecs)\n", "type(nsfg)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result from `read_fwf()` is a `DataFrame`, which is the primary type Pandas uses to store data.\n", "`DataFrame` has a method called `head()` that shows the first 5 rows:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "tags": [] }, "outputs": [], "source": [ "nsfg.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "# NOTE: For the printed version of the book, \n", "# I'm using iloc to show\n", "# the first 5 rows and first 9 columns" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "nsfg.iloc[:5,:7]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first two columns are is `CASEID` and `PREGORDR`, which I mentioned earlier.\n", "The first three rows have the same `CASEID`, so this respondent reported three pregnancies; the values of `PREGORDR` indicate that they are the first, second, and third pregnancies, in that order.\n", "\n", "We will learn more about the other variables as we go along." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition to methods like `head`, a `Dataframe` object has several **attributes**, which are variables associated with the object.\n", "For example, `nsfg` has an attribute called `shape`, which is a tuple containing the number of rows and columns:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "nsfg.shape" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are 9553 rows in this dataset, one for each pregnancy, and 248 columns, one for each variable.\n", "\n", "`nsfg` also has an attribute called `columns`, which contains the column names:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "nsfg.columns" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The column names are stored in an `Index`, which is another Pandas type, similar to a list." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "tags": [] }, "outputs": [], "source": [ "type(nsfg.columns)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Based on the column names, you might be able to guess what some of the variables are, but in general you have to read the documentation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When you work with datasets like the NSFG, it is important to read the documentation carefully. If you interpret a variable incorrectly, you can generate nonsense results and never realize it. So, before we start looking at data, let's get familiar with the NSFG codebook, which describes every variable.\n", "You can download the codebook for this dataset from .\n", "\n", "If you search that document for \"weigh at birth\" you should find these variables related to birth weight.\n", "\n", "* `BIRTHWGT_LB1`: Birthweight in Pounds - 1st baby from this pregnancy\n", "\n", "* `BIRTHWGT_OZ1`: Birthweight in Ounces - 1st baby from this pregnancy\n", "\n", "There are similar variables for a 2nd or 3rd baby, in the case of twins or triplets.\n", "For now we will focus on the first baby from each pregnancy, and we will come back to the issue of multiple births." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Series\n", "\n", "In many ways a `DataFrame` is like a Python dictionary, where the column names are the keys and the columns are the values. You can select a column from a `DataFrame` using the bracket operator, with a string as the key." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "pounds = nsfg['BIRTHWGT_LB1']\n", "type(pounds)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result is a `Series`, which is a Pandas type that represents a single column of data.\n", "In this case the `Series` contains the birth weight, in pounds, for each live birth.\n", "\n", "`head` shows the first five values in the `Series`, the name of the `Series`, and the data type:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "pounds.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of the values is `NaN`, which stands for \"Not a Number\".\n", "`NaN` is a special value used to indicate invalid or missing data.\n", "In this example, the pregnancy did not end in live birth, so birth weight is inapplicable." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** The variable `BIRTHWGT_OZ1` contains the ounces part of birth weight.\n", "\n", "Select the column `'BIRTHWGT_OZ1'` from the `nsfg` `DataFrame` and assign it to a new variable called `ounces`. Then display the first 5 elements of `ounces`." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** The Pandas types we have seen so far are `DataFrame`, `Index`, and `Series`. You can find the documentation of these types at:\n", "\n", "* `DataFrame`: \n", "\n", "* `Index`: \n", "\n", "* `Series`: \n", "\n", "This documentation can be overwhelming; I don't recommend trying to read it all now. But you might want to skim it so you know where to look later." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Validation\n", "\n", "At this point we have identified the columns we need to answer the question and assigned them to variables named `pounds` and `ounces`." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "pounds = nsfg['BIRTHWGT_LB1']\n", "ounces = nsfg['BIRTHWGT_OZ1']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Before we do anything with this data, we have to validate it. One part of validation is confirming that we are interpreting the data correctly.\n", "\n", "We can use the `value_counts` method to see what values appear in `pounds` and how many times each value appears." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "tags": [] }, "outputs": [], "source": [ "pounds.value_counts()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default, the results are sorted with the most frequent value first, but we can use `sort_index` to sort them by value instead, with the lightest babies first and heaviest babies last." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "pounds.value_counts().sort_index()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we'd expect, the most frequent values are 6-8 pounds, but there are some very light babies, a few very heavy babies, and two special values, 98, and 99. According to the codebook, these values indicate that the respondent declined to answer the question (98) or did not know (99).\n", "\n", "We can validate the results by comparing them to the codebook, which lists the values and their frequencies.\n", "\n", "\n", "| value | label | Total |\n", "|-------|----------------|-------|\n", "| . | INAPPLICABLE | 2863 |\n", "| 0-5 | UNDER 6 POUNDS | 901 |\n", "| 6 | 6 POUNDS | 1644 |\n", "| 7 | 7 POUNDS | 2268 |\n", "| 8 | 8 POUNDS | 1287 |\n", "| 9-95 | 9 POUNDS OR MORE | 499 |\n", "| 98 | Refused | 2 |\n", "| 99 | Don't know | 89 |\n", "| | Total | 9553 |\n", "\n", "\n", "The results from `value_counts` agree with the codebook, so we have some confidence that we are reading and interpreting the data correctly." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** In the `nsfg` `DataFrame`, the column `'OUTCOME'` encodes the outcome of each pregnancy as shown below:\n", "\n", "| Value | Meaning |\n", "|---|---|\n", "| 1 | Live birth |\n", "| 2 | Induced abortion |\n", "| 3 | Stillbirth | \n", "| 4 | Miscarriage |\n", "| 5 | Ectopic pregnancy |\n", "| 6 | Current pregnancy |\n", "\n", "Use `value_counts` to display the values in this column and how many times each value appears. Are the results consistent with the codebook?" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary Statistics\n", "\n", "Another way to validate the data is with `describe`, which computes statistics that summarize the data, like the mean, standard deviation, minimum, and maximum.\n", "\n", "Here are the results for `pounds`. " ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "pounds.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`count` is the number of values, not including `NaN`.\n", "For this variable, there are 6690 value that are not `NaN`.\n", "\n", "`mean` and `std` are the mean and standard deviation.\n", "`min` and `max` are the minimum and maximum values, and in between are the 25th, 50th, and 75th percentiles. The 50th percentile is the median.\n", "\n", "The mean is about `8.05`, but that doesn't mean much because it includes the special values 98 and 99. Before we can really compute the mean, we have to replace those values with `NaN` to identify them as missing data.\n", "\n", "The `replace()` method does what we want:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "pounds_clean = pounds.replace([98, 99], np.nan)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`replace` takes a list of the values we want to replace and the value we want to replace them with. `np.nan` means we are getting the special value `NaN` from the NumPy library, which is imported as `np`.\n", "\n", "The result from `replace()` is a new `Series`, which I assign to `pounds_clean`.\n", "If we run `describe` again, we see that `count` is smaller now because it includes only the valid values." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "pounds_clean.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The mean of the new `Series` is about 6.7 pounds.\n", "Remember that the mean of the original `Series` was more than 8 pounds.\n", "It makes a big difference when you remove a few 99-pound babies!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** Use `describe` to summarize `ounces`. \n", "Then use `replace` to replace the special values 98 and 99 with NaN, and assign the result to `ounces_clean`.\n", "Run `describe` again. How much does this cleaning affect the results?" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Series Arithmetic\n", "\n", "Now we want to combine `pounds` and `ounces` into a single `Series` that contains total birth weight.\n", "Arithmetic operators work with `Series` objects; so, for example, to convert `pounds` to ounces, we could write\n", "\n", "`pounds * 16`\n", "\n", "Then we could add in `ounces` like this\n", "\n", "`pounds * 16 + ounces`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** Use `pounds_clean` and `ounces_clean` to compute the total birth weight expressed in kilograms (there are roughly 2.2 pounds per kilogram). What is the mean birth weight in kilograms?" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** For each pregnancy in the NSFG dataset, the variable `'AGECON'` encodes the respondent's age at conception, and `'AGEPREG'` the respondent's age at the end of the pregnancy.\n", "\n", "- Read the documentation of these variables. Are there any special values we have to deal with?\n", "\n", "- Select `'AGECON'` and `'AGEPREG'` and assign them to variables named `agecon` and `agepreg`.\n", "\n", "- Compute the difference, which is an estimate of the duration of the pregnancy.\n", "\n", "- Use `.describe()` to compute the mean duration and other summary statistics.\n", "\n", "Based on the results, it seems like this might not be a good way to estimate the duration of pregnancy. Why not?" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Histograms\n", "\n", "Let's get back to the original question: what is the average birth weight for babies in the U.S.? \n", "As an answer we *could* take the results from the previous section and compute the mean:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "pounds_clean = pounds.replace([98, 99], np.nan)\n", "ounces_clean = ounces.replace([98, 99], np.nan)\n", "\n", "birth_weight = pounds_clean + ounces_clean / 16\n", "birth_weight.mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But it is risky to compute a summary statistic, like the mean, before we look at the whole distribution of values.\n", "\n", "A **distribution** is a set of possible values and their frequencies. One way to visualize a distribution is a **histogram**, which shows values on the `x` axis and their frequencies on the `y` axis.\n", "\n", "`Series` provides a `hist` method that makes histograms.\n", "And we can use Matplotlib to label the axes." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "birth_weight.hist(bins=30)\n", "plt.xlabel('Birth weight in pounds')\n", "plt.ylabel('Number of live births')\n", "plt.title('Distribution of U.S. birth weight');" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The keyword argument, `bins`, tells `hist` to divide the range of weights into 30 intervals, called **bins**, and count how many values fall in each bin.\n", "The `x` axis is birth weight in pounds; the `y` axis is the number of births in each bin.\n", "\n", "The distribution looks a little like a bell curve, but the tail is longer on the left than on the right; that is, there are more light babies than heavy babies.\n", "That makes sense, because the distribution includes some babies that were born preterm. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** `hist` takes keyword arguments that specify the type and appearance of the histogram. Find the documentation of `hist` and see if you can figure out how to plot the histogram as an unfilled line against a background with no grid lines." ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** As we saw in a previous exercise, the NSFG dataset includes a column called `AGECON` that records age at conception for each pregnancy. \n", "\n", "- Select this column from the `DataFrame` and plot the histogram of the values with 20 bins.\n", "\n", "- Label the `x` and `y` axes appropriately." ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Boolean Series\n", "\n", "We have seen that the distribution of birth weights is **skewed** to the left; that is, there are more light babies than heavy ones and they are farther from the mean.\n", "That's because preterm babies tend to be lighter. The most common duration for pregnancy is 39 weeks, which is \"full term\"; \"preterm\" is usually defined to be less than 37 weeks.\n", "\n", "To see which babies are preterm, we can use `PRGLNGTH`, which records pregnancy length in weeks and compute it to `37`." ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "preterm = (nsfg['PRGLNGTH'] < 37)\n", "preterm.dtype" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When you compare a `Series` to a value, the result is a Boolean `Series`; that is, a `Series` where each element is a Boolean value, `True` or `False`. In this case, it's `True` for each preterm baby and `False` otherwise. We can use `head` to see the first 5 elements." ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "preterm.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you compute the sum of a Boolean `Series`, it treats `True` as 1 and `False` as 0, so the sum is the number of `True` values, which is the number of preterm babies." ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "preterm.sum()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you compute the mean of a Boolean `Series`, you get the *fraction* of `True` values.\n", "In this case, it's about 0.38; that is, about 38% of the pregnancies are less than 37 weeks." ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "preterm.mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, this result might be misleading because it includes all pregnancy outcomes, not just live births.\n", "We can create another Boolean `Series` to indicate which pregnancies ended in live birth:" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "live = (nsfg['OUTCOME'] == 1)\n", "live.mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we can use the operator `&`, which represents the logical AND operation, to identify pregnancies where the outcome is a live birth and preterm: " ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "live_preterm = (live & preterm)\n", "live_preterm.mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "About 9% of all pregnancies resulted in a preterm live birth." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** Of all live births, what fraction are preterm?" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The other common logical operators are:\n", " \n", "* `|`, which represents the logical OR operation; for example `live | preterm` is true if either `live` is true, or `preterm` is true, or both.\n", "\n", "* `~`, which represents the logical NOT operation; for example `~live` is true if `live` is false or `NaN`.\n", "\n", "The logical operators treat `NaN` the same as `False`, so you should be careful about using the NOT operator with a Series that contains `NaN` values.\n", "For example, `~preterm` would include not just full term pregnancies, but also pregnancies with unknown length." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** Of all pregnancies, what fraction are full term, that is, 37 weeks or more?\n", "Of all live births, what fraction are full term?" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Filtering Data\n", "\n", "We can use a Boolean `Series` as a filter; that is, we can select only rows that satisfy a condition or meet some criterion.\n", "For example, we can use `preterm` and the bracket operator to select values from `birth_weight`, so `preterm_weight` gets birth weights for preterm babies. " ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "preterm_weight = birth_weight[preterm]\n", "preterm_weight.mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To select full-term babies, we can create a Boolean `Series` like this:" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "fullterm = (nsfg['PRGLNGTH'] >= 37)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And use it to select birth weights for full term babies:" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [], "source": [ "full_term_weight = birth_weight[fullterm]\n", "full_term_weight.mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As expected, full term babies are heavier, on average, than preterm babies.\n", "To be more explicit, we could also limit the results to live births, like this:" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [ "full_term_weight = birth_weight[live & fullterm]\n", "full_term_weight.mean()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But in this case we get the same result because `birth_weight` is only valid for live births." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** Let's see if there is a difference in weight between single births and multiple births (twins, triplets, etc.).\n", "The variable `NBRNALIV` represents the number of babies born alive from a single pregnancy." ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [], "source": [ "nbrnaliv = nsfg['NBRNALIV']\n", "nbrnaliv.value_counts()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use `nbrnaliv` and `live` to create a Boolean series called `multiple` that is true for multiple live births.\n", "Of all live births, what fraction are multiple births?" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** Make a Boolean series called `single` that is true for single live births.\n", "Of all single births, what fraction are preterm?\n", "Of all multiple births, what fraction are preterm?" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** What is the average birth weight for live, single, full-term births?" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Weighted Means\n", "\n", "We are almost done, but there's one more problem we have to solve: oversampling.\n", "\n", "The NSFG is not exactly representative of the U.S. population. By design, some groups are more likely to appear in the sample than others; that is, they are **oversampled**. Oversampling helps to ensure that you have enough people in every subgroup to get reliable statistics, but it makes data analysis a little more complicated.\n", "\n", "Each pregnancy in the dataset has a **sampling weight** that indicates how many pregnancies it represents. In `nsfg`, the sampling weight is stored in a column named `wgt2015_2017`.\n", "Here's what it looks like." ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "sampling_weight = nsfg['WGT2015_2017']\n", "sampling_weight.describe()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The median value (50th percentile) in this column is about 7292, which means that a pregnancy with that weight represents 7292 total pregnancies in the population.\n", "But the range of values is wide, so some rows represent many more pregnancies than others.\n", "\n", "To take these weights into account, we can compute a **weighted mean**. Here are the steps:\n", "\n", "1. Multiply the birth weights for each pregnancy by the sampling weights and add up the products.\n", "\n", "2. Add up the sampling weights.\n", "\n", "3. Divide the first sum by the second.\n", "\n", "To do this correctly, we have to be careful with missing data.\n", "To help with that, we'll use two `Series` methods, `isna` and `notna`.\n", "\n", "`isna` returns a Boolean `Series` that is `True` where the corresponding value is `NaN`." ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [], "source": [ "missing = birth_weight.isna()\n", "missing.sum()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In `birth_weight` there are 3013 missing values (mostly for pregnancies that did not end in live birth).\n", "\n", "`notna` returns a Boolean `Series` that is `True` where the corresponding value is *not* `NaN`." ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [], "source": [ "valid = birth_weight.notna()\n", "valid.sum()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can combine `valid` with the other Boolean `Series` we have computed to identify single, full term, live births with valid birth weights." ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [], "source": [ "single = (nbrnaliv == 1)\n", "selected = valid & live & single & fullterm\n", "selected.sum()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can finish off this computation as an exercise." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Exercise:** Use `selected`, `birth_weight`, and `sampling_weight` to compute the weighted mean of birth weight for live, single, full term births.\n", "\n", "You should find that the weighted mean is a little higher than the unweighted mean we computed in the previous section. That's because the groups that are oversampled in the NSFG tend to have lighter babies, on average." ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [], "source": [ "# Solution goes here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary\n", "\n", "This chapter poses what seems like a simple question: what is the average birth weight of babies in the United States?\n", "\n", "To answer it, we found an appropriate dataset and read the files. Then we validated the data and dealt with special values, missing data, and errors.\n", "To explore the data, we used `value_counts`, `hist`, `describe`, and other Pandas methods.\n", "And to select relevant data, we used Boolean `Series`.\n", "\n", "Along the way, we had to think more about the question. What do we mean by \"average\", and which babies should we include? Should we include all live births or exclude preterm babies or multiple births?\n", "\n", "And we had to think about the sampling process. By design, the NSFG respondents are not representative of the U.S. population, but we can use sampling weights to correct for this effect.\n", "\n", "Even a simple question can be a challenging data science project." ] }, { "cell_type": "markdown", "metadata": { "tags": [] }, "source": [ "*Elements of Data Science*\n", "\n", "Copyright 2021 [Allen B. Downey](https://allendowney.com)\n", "\n", "License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" ] } ], "metadata": { "celltoolbar": "Tags", "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.13" } }, "nbformat": 4, "nbformat_minor": 2 }