-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcensus_data.py
More file actions
224 lines (199 loc) · 8.42 KB
/
Copy pathcensus_data.py
File metadata and controls
224 lines (199 loc) · 8.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""
Census data aggregation pipeline for the Displaced Voices project.
Fetches ACS 5-Year data for Maricopa County, AZ and merges with eviction records.
"""
import logging
import pandas as pd
import requests
from io import BytesIO
from config import get_api_key
log = logging.getLogger(__name__)
EVICTION_URL = (
"https://raw.githubusercontent.com/UnitForDataScience/Projects-Spring-2025"
"/refs/heads/main/Displaced%20Voices/Data/data_geocoded.csv"
)
RACE_COLS = [
"White Alone",
"Black Alone",
"Hispanic or Latino",
"American Indian or Alaska Native Alone",
"Asian Alone",
"Native Hawaiian or Pacific Islander Alone",
"Some other race",
'Mixed race (exluding "Some other race")',
]
def _report_anomalies(df, label, year):
numeric_cols = df.select_dtypes(include="number").columns
n_total = len(df)
found = False
for col in numeric_cols:
n_bad = (df[col] < 0).sum()
if n_bad > 0:
log.warning(
"[%s] %s: %d/%d tracts have %s < 0 — treated as missing",
year, label, n_bad, n_total, col,
)
found = True
if not found:
log.info("[%s] %s: no anomalies detected across %d numeric columns", year, label, len(numeric_cols))
def _fetch(codes, year, state, county, api_key):
if isinstance(codes, list):
codes = ",".join(codes)
url = (
f"https://api.census.gov/data/{year}/acs/acs5"
f"?get=NAME,{codes}&for=tract:*"
f"&in=state:{state}&in=county:{county}&key={api_key}"
)
r = requests.get(url)
r.raise_for_status()
data = r.json()
return pd.DataFrame(data[1:], columns=data[0])
def fetch_median_income(year, state, county, api_key):
df = _fetch("B19013_001E", year, state, county, api_key)
df["B19013_001E"] = df["B19013_001E"].astype(int)
df.rename(columns={"B19013_001E": "medianIncome"}, inplace=True)
df.drop(columns="NAME", inplace=True)
_report_anomalies(df, "fetch_median_income", year)
df = df.loc[df["medianIncome"] > 0].copy()
df[["state", "county", "tract"]] = df[["state", "county", "tract"]].astype(str)
df["GeoID"] = df["state"] + df["county"] + df["tract"]
log.info("fetch_median_income: %d rows → medianIncome", len(df))
return df
def fetch_occupation(year, state, county, api_key):
codes = ["B25008_001E", "B25008_002E", "B25008_003E"]
df = _fetch(codes, year, state, county, api_key)
df[codes] = df[codes].astype(int)
_report_anomalies(df, "fetch_occupation", year)
df["OwnerOccupied"] = df["B25008_002E"] / df["B25008_001E"]
df["RenterOccupied"] = df["B25008_003E"] / df["B25008_001E"]
df.drop(columns=codes + ["NAME"], inplace=True)
df["LiveType"] = df[["OwnerOccupied", "RenterOccupied"]].idxmax(axis=1)
df[["state", "county", "tract"]] = df[["state", "county", "tract"]].astype(str)
df["GeoID"] = df["state"] + df["county"] + df["tract"]
log.info("fetch_occupation: %d rows → OwnerOccupied, RenterOccupied", len(df))
return df
def fetch_burden(year, state, county, api_key):
codes = [f"B25070_{str(i).zfill(3)}E" for i in range(1, 11)]
df = _fetch(codes, year, state, county, api_key)
df[codes] = df[codes].astype(int)
_report_anomalies(df, "fetch_burden", year)
df = df.loc[df["B25070_001E"] > 0].copy()
total = df["B25070_001E"]
df["lowBurdan"] = (df["B25070_002E"] + df["B25070_003E"]) / total
df["moderateBurdan"] = (df["B25070_004E"] + df["B25070_005E"]) / total
df["costBurdan"] = (
df[["B25070_006E", "B25070_007E", "B25070_008E", "B25070_009E"]].sum(axis=1)
) / total
df["highBurdan"] = df["B25070_010E"] / total
df.drop(columns=codes + ["NAME"], inplace=True)
df["burden"] = df[
["lowBurdan", "moderateBurdan", "costBurdan", "highBurdan"]
].idxmax(axis=1)
df[["state", "county", "tract"]] = df[["state", "county", "tract"]].astype(str)
df["GeoID"] = df["state"] + df["county"] + df["tract"]
log.info("fetch_burden: %d rows → lowBurdan, moderateBurdan, costBurdan, highBurdan", len(df))
return df
def fetch_race(year, state, county, api_key):
codes = [
"B02001_001E", "B02001_002E", "B02001_003E", "B03001_003E",
"B02001_004E", "B02001_005E", "B02001_006E", "B02001_007E", "B02001_009E",
]
df = _fetch(codes, year, state, county, api_key)
for col in codes:
df[col] = df[col].astype(float)
total = df["B02001_001E"]
_report_anomalies(df, "fetch_race", year)
for col in codes[1:]:
df[col] = df[col] / total
rename_map = {
"B02001_001E": "Total",
"B02001_002E": "White Alone",
"B02001_003E": "Black Alone",
"B03001_003E": "Hispanic or Latino",
"B02001_004E": "American Indian or Alaska Native Alone",
"B02001_005E": "Asian Alone",
"B02001_006E": "Native Hawaiian or Pacific Islander Alone",
"B02001_007E": "Some other race",
"B02001_009E": 'Mixed race (exluding "Some other race")',
}
df.rename(columns=rename_map, inplace=True)
df["Majority"] = df[RACE_COLS].idxmax(axis=1)
df[["state", "county", "tract"]] = df[["state", "county", "tract"]].astype(str)
df["GeoID"] = df["state"] + df["county"] + df["tract"]
df.drop(columns=["NAME", "Total"], inplace=True)
log.info("fetch_race: %d rows → %s", len(df), ", ".join(RACE_COLS))
return df
def fetch_house_structure(year, state, county, api_key):
codes = [
"B25032_001E", "B25032_003E", "B25032_004E", "B25032_005E", "B25032_006E",
"B25032_007E", "B25032_008E", "B25032_009E", "B25032_010E",
"B25032_011E", "B25032_012E",
]
df = _fetch(codes, year, state, county, api_key)
for col in codes:
df[col] = df[col].astype(int)
total = df["B25032_001E"]
_report_anomalies(df, "fetch_house_structure", year)
result = pd.DataFrame({
"Single-family homes": (df["B25032_003E"] + df["B25032_004E"]) / total,
"Small multi-unit buildings (2-4 units)": (
df["B25032_005E"] + df["B25032_006E"]
) / total,
"Larger apartment complexes (5+ units)": (
df["B25032_007E"] + df["B25032_008E"]
+ df["B25032_009E"] + df["B25032_010E"]
) / total,
"Mobile homes, boats, RVs, etc.": (
df["B25032_011E"] + df["B25032_012E"]
) / total,
})
result["majorHouseType"] = result[[
"Single-family homes",
"Small multi-unit buildings (2-4 units)",
"Larger apartment complexes (5+ units)",
]].idxmax(axis=1)
result[["state", "county", "tract"]] = df[["state", "county", "tract"]].values
result = result.loc[total.values > 0].copy()
result[["state", "county", "tract"]] = result[["state", "county", "tract"]].astype(str)
result["GeoID"] = result["state"] + result["county"] + result["tract"]
log.info("fetch_house_structure: %d rows → %s", len(result), ", ".join(result.columns))
return result
def fetch_eviction(url=EVICTION_URL):
r = requests.get(url, stream=True)
r.raise_for_status()
df = pd.read_csv(BytesIO(r.content))
df.dropna(subset=["geoid"], inplace=True)
df = df[["geoid", "zip_code", "type"]].copy()
df["zip_code"] = df["zip_code"].astype(str)
df["GeoID"] = df["geoid"].astype(int).astype(str).str.zfill(11)
counts = df.groupby(["GeoID", "zip_code"])["type"].count().reset_index()
counts.rename(columns={"type": "filedEviction"}, inplace=True)
return counts
def build_full_dataset(year="2023", state="04", county="013"):
"""Fetch and merge all census tables with eviction counts."""
api_key = get_api_key()
drop_geo = ["state", "county", "tract"]
df = (
fetch_median_income(year, state, county, api_key)
.merge(
fetch_house_structure(year, state, county, api_key).drop(columns=drop_geo),
how="inner", on="GeoID",
)
.merge(
fetch_burden(year, state, county, api_key).drop(columns=drop_geo),
how="inner", on="GeoID",
)
.merge(
fetch_occupation(year, state, county, api_key).drop(columns=drop_geo),
how="inner", on="GeoID",
)
.merge(
fetch_race(year, state, county, api_key).drop(columns=drop_geo),
how="inner", on="GeoID",
)
)
eviction = fetch_eviction()
df = eviction.merge(df, how="right", on="GeoID")
df["filedEviction"] = df["filedEviction"].fillna(0).astype(int)
df["zip_code"] = df["zip_code"].fillna("N/A")
return df