import pandas as pd
nes = pd.read_csv("nes2020_subset.csv")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):
Exercise 1 — Inspecting a DataFrame
After loading the data:
- Print the first 5 rows.
- Print the column names.
- Print the number of rows and columns.
- Print summary statistics for all numeric columns.
# your code hereExercise 2 — Filtering
Using boolean filtering on the nes DataFrame:
- Create a new DataFrame containing only respondents with a Biden feeling thermometer (
ft_biden) above 80. - How many rows are in that filtered DataFrame?
- What’s the mean Trump feeling thermometer (
ft_trump) among those high-Biden respondents?
# your code hereExercise 3 — Summary by group
Using groupby (which we touched on briefly):
- Group the data by
freetrade(attitudes toward free trade). - Compute the mean
ft_police(police feeling thermometer) for each free-trade group. - 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:
- Print the mean of the new column.
- Print the number of respondents where this difference is positive (favors Biden).
# your code hereExercise 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:
- Sort the DataFrame by
budget_bdescending. - Filter to policies with
approve_pct > 60. - Compute the average approval percentage across all five policies.
# your code hereExercise 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:*
- Use
requests.get()to fetch the URL. - Check that the status code is 200.
- Convert the response to JSON.
- 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 hereExercise 7 — Putting it together: API → DataFrame
Building on Exercise 6:
- Convert the list-of-lists response into a pandas DataFrame, using the first row as the column names.
- Convert the
P1_001Ncolumn (population) from string to integer. - Sort the DataFrame by population descending.
- Print the top 10 most populous states.
# your code here