Day 4 — Optional Exercises

pandas and APIs

Solutions are in Day_4_Solutions.qmd.

For the pandas exercises, you’ll use the same ANES 2020 subset you saw in class. Load it like this (path may vary depending on where you’re running):

import pandas as pd
nes = pd.read_csv("nes2020_subset.csv")

Exercise 1 — Inspecting a DataFrame

After loading the data:

  1. Print the first 5 rows.
  2. Print the column names.
  3. Print the number of rows and columns.
  4. Print summary statistics for all numeric columns.
# your code here

Exercise 2 — Filtering

Using boolean filtering on the nes DataFrame:

  1. Create a new DataFrame containing only respondents with a Biden feeling thermometer (ft_biden) above 80.
  2. How many rows are in that filtered DataFrame?
  3. What’s the mean Trump feeling thermometer (ft_trump) among those high-Biden respondents?
# your code here

Exercise 3 — Summary by group

Using groupby (which we touched on briefly):

  1. Group the data by freetrade (attitudes toward free trade).
  2. Compute the mean ft_police (police feeling thermometer) for each free-trade group.
  3. Print the result.
# your code here

(If you didn’t see groupby in class, the syntax is nes.groupby("freetrade")["ft_police"].mean().)


Exercise 4 — Creating a new column

Add a new column to nes called biden_minus_trump that contains the difference between each respondent’s Biden and Trump thermometer ratings. Then:

  1. Print the mean of the new column.
  2. Print the number of respondents where this difference is positive (favors Biden).
# your code here

Exercise 5 — A small DataFrame from scratch

Build a DataFrame from this dictionary:

data = {
    "policy": ["education", "healthcare", "defense", "infrastructure", "climate"],
    "budget_b": [82, 1670, 850, 244, 75],   # in billions
    "approve_pct": [68, 54, 49, 71, 62],
}

Then:

  1. Sort the DataFrame by budget_b descending.
  2. Filter to policies with approve_pct > 60.
  3. Compute the average approval percentage across all five policies.
# your code here

Exercise 6 — Hitting an API

The U.S. Census Bureau has a free public API. Use the requests library to hit this endpoint, which returns the total population of every state from the 2020 decennial census:

https://api.census.gov/data/2020/dec/pl?get=NAME,P1_001N&for=state:*
  1. Use requests.get() to fetch the URL.
  2. Check that the status code is 200.
  3. Convert the response to JSON.
  4. Print the first 5 rows.

(The response is a list of lists — the first row is column headers, then each subsequent row is one state.)

import requests

# your code here

Exercise 7 — Putting it together: API → DataFrame

Building on Exercise 6:

  1. Convert the list-of-lists response into a pandas DataFrame, using the first row as the column names.
  2. Convert the P1_001N column (population) from string to integer.
  3. Sort the DataFrame by population descending.
  4. Print the top 10 most populous states.
# your code here