-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_geography.py
More file actions
2549 lines (2099 loc) · 64.5 KB
/
Copy path01_geography.py
File metadata and controls
2549 lines (2099 loc) · 64.5 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import marimo
__generated_with = "0.20.2"
app = marimo.App(width="medium")
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# California counties' precinct workflow
This notebook standardizes the geographic precinct files from each county. It re-projects everything into NAD83/California Albers, and ensures that each feature has the following attributes:
* `county`
* `precinct_id` - The precinct ID
* `precinct_name` - The human-readable name provided by the county or is otherwise an empty string
""")
return
@app.cell
def _():
import re
import geopandas as gpd
import marimo as mo
import pandas as pd
import pdfplumber
return gpd, mo, pd, pdfplumber, re
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# Constants
""")
return
@app.cell
def _():
PROJECTED_CRS = (
"EPSG:3310" # NAD83 / California Albers (good for area calculations in CA)
)
return (PROJECTED_CRS,)
@app.cell
def _():
OUTPUT_COLUMNS = ["county", "precinct_id", "precinct_name", "geometry"]
COMBINED_OUTPUT_PATH = "outputs/precincts.gpkg"
COMBINED_OUTPUT_DRIVER = "GPKG"
return COMBINED_OUTPUT_DRIVER, COMBINED_OUTPUT_PATH, OUTPUT_COLUMNS
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# Merge and export
""")
return
@app.cell
def _(combined_reordered):
# show the counties that are included in the workflow
combined_reordered.plot()
return
@app.cell
def _(
alameda,
amador,
butte,
colusa,
contra_costa,
fresno,
glenn,
humboldt,
imperial,
inyo,
kern,
lake,
los_angeles,
madera,
marin,
mariposa,
mendocino,
merced,
modoc,
mono,
monterey,
napa,
nevada,
orange,
placer,
riverside,
sacramento,
san_benito,
san_bernardino,
san_diego,
san_francisco,
san_joaquin,
san_luis_obispo,
san_mateo,
santa_barbara,
santa_clara,
santa_cruz,
shasta,
sierra,
siskiyou,
solano,
sonoma,
stanislaus,
sutter,
tehama,
tulare,
tuolumne,
ventura,
yolo,
yuba,
):
COUNTIES_GDFS = [
alameda,
amador,
butte,
colusa,
contra_costa,
fresno,
glenn,
humboldt,
imperial,
inyo,
kern,
lake,
los_angeles,
madera,
marin,
mariposa,
mendocino,
merced,
modoc,
mono,
monterey,
napa,
nevada,
orange,
placer,
riverside,
sacramento,
san_benito,
san_bernardino,
san_diego,
san_francisco,
san_joaquin,
san_luis_obispo,
san_mateo,
santa_barbara,
santa_clara,
santa_cruz,
shasta,
sierra,
siskiyou,
solano,
sonoma,
stanislaus,
sutter,
tehama,
tulare,
tuolumne,
ventura,
yolo,
yuba,
]
return (COUNTIES_GDFS,)
@app.cell
def _(
COMBINED_OUTPUT_DRIVER,
COMBINED_OUTPUT_PATH,
COUNTIES_GDFS,
OUTPUT_COLUMNS,
pd,
):
# create a new data frame from the data frames for each county
combined = pd.concat(COUNTIES_GDFS)
# make sure any missing "precinct_name" values are empty strings
combined = combined.fillna(value={"precinct_name": ""})
# reorder the columns to make it more readable
combined_reordered = combined[OUTPUT_COLUMNS]
dupes = check_duplicates(combined_reordered)
# save the reordered results to a file at COMBINED_OUTPUT_PATH
combined_reordered.to_file(COMBINED_OUTPUT_PATH, driver=COMBINED_OUTPUT_DRIVER)
print(f"Saved combined precincts to {COMBINED_OUTPUT_PATH}")
return (combined_reordered,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# Helper functions
""")
return
@app.function
def check_duplicates(df, columns_to_check=None):
"""
Check for duplicate entries in the DataFrame based on specified columns.
If duplicates are found, print a descriptive message listing the counties with duplicate IDs.
Returns the duplicate rows sorted by the specified columns if possible; otherwise, returns unsorted duplicates.
Parameters:
df (pd.DataFrame): The input DataFrame to check for duplicates.
columns_to_check (list): List of column names to identify duplicates. Defaults to ["county", "precinct_id"].
Returns:
pd.DataFrame | None: DataFrame of duplicate rows if found (sorted if possible), otherwise None.
"""
if columns_to_check is None:
columns_to_check = ["county", "precinct_id"]
# Identify duplicate rows based on "county" and "precinct_id"
duplicates = df[df.duplicated(subset=columns_to_check, keep=False)]
if not duplicates.empty:
# Get the list of counties that have duplicate precinct IDs
duplicate_counties = duplicates["county"].unique().tolist()
print(
f"Duplicate precinct IDs found in the following counties: {', '.join(sorted(duplicate_counties))}"
)
# Attempt to sort by precinct_id, but handle unsortable cases (e.g., mixed str/float)
try:
return duplicates.sort_values(columns_to_check)
except TypeError:
print(
"Sorting by (county, precinct_id) threw a type error, returning unsorted dupe data"
)
return duplicates # Return unsorted if sorting fails
else:
return None
@app.function
def validate_crosswalk_merge(
merged, debug_prefix="", left_only_cols=None, right_only_cols=None
):
"""
Validate outer merge of GIS and crosswalk. Export unmatched rows to debug
CSVs. Returns only rows with _merge == "both", with _merge dropped.
Parameters:
merged (pd.DataFrame): The merged DataFrame containing GIS and crosswalk data with a "_merge" column
indicating the source of each row ("left_only", "right_only", or "both"). Can be applied by
setting the indicator parameter in pd.merge. Merge also requires left to be GIS precincts and
right to be the crosswalk data precincts
debug_prefix (str): A string prefix used to name the debug output files for unmatched precincts.
left_only_cols (list of str, optional): List of column names to include in the debug CSV for records
present only in the GIS data (default is all columns).
right_only_cols (list of str, optional): List of column names to include in the debug CSV for records
present only in the crosswalk data (default is all columns).
Returns:
pd.DataFrame: A filtered DataFrame containing only rows that matched in both datasets
(i.e., where _merge == "both"), with the "_merge" column dropped.
"""
checks = {
"left_only": {
"message": "GIS precincts did not match in the crosswalk data.",
"cols": left_only_cols if left_only_cols else merged.columns,
"suffix": "unmatched_precincts",
},
"right_only": {
"message": "crosswalk component precincts have no match in the geographic data.",
"cols": right_only_cols if right_only_cols else merged.columns,
"suffix": "crosswalk_only_precincts",
},
}
for merge_val, config in checks.items():
subset = merged[merged["_merge"] == merge_val]
if len(subset) != 0:
print(f"Warning: {len(subset)} {config['message']}")
fp = f"debug/{debug_prefix}_{config['suffix']}.csv"
subset[config["cols"]].to_csv(fp, index=False)
print(f"Exported to {fp}")
return merged[merged["_merge"] == "both"].drop(columns=["_merge"])
@app.function
def alter_df(df, county, rename=None, drop=None):
"""
Add county column, optionally rename and drop columns. Returns the modified DataFrame.
"""
df["county"] = county
if rename:
df = df.rename(
columns=rename,
)
if drop:
df = df.drop(
labels=drop,
axis="columns",
errors="ignore",
)
return df
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# Extract and transform by county
Each county's independent election administrator produces an election precincts map that needs to be read in and transformed into our standardized format
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## Alameda
""")
return
@app.cell
def _(PROJECTED_CRS, gpd):
# read in the source file with geopandas and reproject to PROJECTED_CRS
_GIS_FP = "inputs/counties/alameda/precincts/Consolidated_Precincts_-_November_4%2C_2025_Statewide_Special_Election.geojson"
alameda = gpd.read_file(_GIS_FP).to_crs(PROJECTED_CRS)
# use alter_df to clean, renaming some columns and dropping others
alameda = alter_df(
df=alameda,
county="Alameda",
rename={"Precinct_ID": "precinct_id"},
drop=[
"Election_Name",
"Precinct_ID",
"OBJECTID",
"Shape__Area",
"Shape__Length",
],
)
# look at the first five rows
alameda.head()
return (alameda,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## Amador
""")
return
@app.cell
def _(PROJECTED_CRS, gpd):
_GIS_FP = (
"inputs/counties/amador/precincts/VotingDistricts_2021_Updated3-18-22.zip"
)
amador = gpd.read_file(_GIS_FP).to_crs(PROJECTED_CRS)
# the spatial data is more granular than the results so we should combine
# features based on the value in the "CP" column
# spatial data is likely voting precincts, and the results data is reported using Consolidated Precincts.
# We are (safely) assuming "CP" is consolidated precincts and dissolving the data appropriately
amador = amador.dissolve(by="CP").reset_index()
amador = alter_df(
df=amador,
county="Amador",
rename={"CP": "precinct_id"},
drop=[
"PRECINCT",
"LOCATION",
"SUPDIST",
"POLLPLACE",
"POLLADDR",
"POLLCITY",
"POLLSTATE",
"POLLZIP",
"SHAPE_Leng",
"SHAPE_Area",
],
)
amador.head()
return (amador,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## Butte
""")
return
@app.cell
def _(PROJECTED_CRS, gpd):
_GIS_FP = "inputs/counties/butte/precincts/Butte Precincts 2025.kmz"
butte = gpd.read_file(_GIS_FP).to_crs(PROJECTED_CRS)
butte = alter_df(
df=butte,
county="Butte",
# note: the id and name columns in the source data unintuitively have the expected precinct name and id swapped
rename={"Name": "precinct_id", "id": "precinct_name"},
drop=[
"id",
"Name",
"description",
"timestamp",
"begin",
"end",
"altitudeMode",
"tessellate",
"extrude",
"visibility",
"drawOrder",
"icon",
],
)
butte.head()
return (butte,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## Colusa
""")
return
@app.cell
def _(PROJECTED_CRS, gpd):
_GIS_FP = "inputs/counties/colusa/precincts/Voting Precincts - 2020.shp"
colusa = gpd.read_file(_GIS_FP).to_crs(PROJECTED_CRS)
colusa = alter_df(
df=colusa,
county="Colusa",
rename={"PRECINCTNU": "precinct_id", "PRECINCT": "precinct_name"},
drop=["DISTRICT"],
)
colusa.head()
return (colusa,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## Contra Costa
Precincts with zero registered voters are filtered out, because these precincts are not included in the official results data. [Read more issue #47](https://github.com/CalMatters/data-prop50-results/issues/47)
""")
return
@app.cell
def _(PROJECTED_CRS, gpd):
_GIS_FP = "inputs/counties/contra_costa/precincts/PrecinctSet_PDMJ017.json"
_ZERO_REGISTRATION_FLAG = 1
contra_costa = gpd.read_file(_GIS_FP).to_crs(PROJECTED_CRS)
has_voters = contra_costa["iZeroRegistrationPct"] != _ZERO_REGISTRATION_FLAG
contra_costa = contra_costa[has_voters].copy()
contra_costa = alter_df(
df=contra_costa,
county="Contra Costa",
rename={"sPrecinctID": "precinct_id", "szPrecinctName": "precinct_name"},
drop=[
"OBJECTID",
"sPrecinctPortion",
"sMapNumber",
"szRemarks",
"szCityName",
"iZeroRegistrationPct",
"iLanguageTargetedPct",
"geomPrecinct",
"szPrecinctSetDesc",
"created_user",
"created_date",
"last_edited_user",
"last_edited_date",
"GlobalID",
"Shape__Area",
"Shape__Length",
],
)
contra_costa.head()
return (contra_costa,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## Fresno
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
Extract crosswalk data to convert the geographic file to match the expected precinct in the results data
""")
return
@app.cell
def _():
def _strip_lang_signifier_from_registration_precinct_id(precinct_id):
# some precincts have a suffix such as "_H" or "_L"
# which signify the major language in that precinct
# we can remove that to complete our merge
suffixes_to_remove = [
"_C",
"_H",
"_L",
"_P",
"_T",
"_V",
"_KH",
"_KO",
"KO",
]
for suffix in suffixes_to_remove:
precinct_id = precinct_id.replace(suffix, "")
return precinct_id
def extract_fresno_crosswalk_pdf_page(
page, last_seen_results_precinct_id=None
):
"""
Extracts the crosswalk from PDF pages the crosswalk connects "Regular Precincts" which are used for voter registration (and therefore called registration_precincts in this code) to "Voting Precincts" which are used for results (and therefore called results_precincts in this code)
Parameters:
page (pdfplumber.Page): The PDF page to extract
Returns:
list: A list of objects, each with "registration_precinct" and "results_precinct"
str|none: latest value for last_seen_results_precinct_id
"""
# the shapefile from the county only has "Regular Precincts"
# but the results file only has "Voting Precincts"
# create a list to store the page's data in
page_rows = []
# get all of the text from the page and split it into lines
page_text = page.extract_text()
page_lines = page_text.splitlines()
# define constants for line split counts
REGULAR_LINE_SPLIT_COUNT = 4
LINE_WITH_RESULTS_ID_SPLIT_COUNT = 7
# define constants for index positions
REGISTRATION_PRECINCT_INDEX_REGULAR = 2
REGISTRATION_PRECINCT_INDEX_WITH_RESULTS = 5
RESULTS_PRECINCT_ID_INDEX = 0
def _extract_precinct_from_page_line(line, last_seen_id):
line_split = line.split(" ")
line_split_count = len(line_split)
row = None
# regular data lines have 4 elements after the split
if line_split_count == REGULAR_LINE_SPLIT_COUNT:
row = {
"registration_precinct": _strip_lang_signifier_from_registration_precinct_id(
line_split[REGISTRATION_PRECINCT_INDEX_REGULAR]
),
"results_precinct": last_seen_id,
}
return row, last_seen_id
# if the data has 7 elements after the split that means it has
# the results precinct id
elif line_split_count == LINE_WITH_RESULTS_ID_SPLIT_COUNT:
new_last_seen_id = str(line_split[RESULTS_PRECINCT_ID_INDEX])
row = {
"registration_precinct": _strip_lang_signifier_from_registration_precinct_id(
line_split[REGISTRATION_PRECINCT_INDEX_WITH_RESULTS]
),
"results_precinct": new_last_seen_id,
}
return row, new_last_seen_id
return None, last_seen_id
# go through each line and split it on white space
for line in page_lines:
row, last_seen_results_precinct_id = _extract_precinct_from_page_line(
line, last_seen_results_precinct_id
)
if row is not None:
page_rows.append(row)
return page_rows, last_seen_results_precinct_id
return (extract_fresno_crosswalk_pdf_page,)
@app.cell
def _(extract_fresno_crosswalk_pdf_page, pd, pdfplumber):
last_seen_results_precinct_id = None
# create a variable to store all of the extracted row
fresno_page_rows = []
# Define bounding box coordinates for left and right sections
_LEFT_CROP_BOUNDS = [15, 30, 388, 580]
_RIGHT_CROP_BOUNDS = [390, 30, 760, 580]
_CROSSWALK_PDF_PATH = (
"inputs/counties/fresno/ewmr008_votabsregpctxref-2025.pdf"
)
with pdfplumber.open(_CROSSWALK_PDF_PATH) as fresno_crosswalk_pdf:
for fresno_crosswalk_page in fresno_crosswalk_pdf.pages:
# the source pdf has a table that is split into two halves
# crop the page into two sections
left_page = fresno_crosswalk_page.crop(bbox=_LEFT_CROP_BOUNDS)
right_page = fresno_crosswalk_page.crop(bbox=_RIGHT_CROP_BOUNDS)
# extract the text from each section
left_page_extracted, last_seen_results_precinct_id = (
extract_fresno_crosswalk_pdf_page(
left_page, last_seen_results_precinct_id
)
)
right_page_extracted, last_seen_results_precinct_id = (
extract_fresno_crosswalk_pdf_page(
right_page, last_seen_results_precinct_id
)
)
# and add the results of both to our list for all pages
fresno_page_rows.extend(left_page_extracted)
fresno_page_rows.extend(right_page_extracted)
# turn the resulting list into a dataframe
fresno_page_rows = pd.DataFrame(fresno_page_rows)
return (fresno_page_rows,)
@app.cell
def _(PROJECTED_CRS, fresno_page_rows, gpd):
# use fresno registration precincts
_GIS_FP = "inputs/counties/fresno/precincts/ELECTIONS_PRECINCT_VW.zip"
fresno = gpd.read_file(_GIS_FP).to_crs(PROJECTED_CRS)
# create a column to merge on
fresno["registration_precinct"] = fresno["EIMS_PRCT"]
# merge precincts with crosswalk data
fresno_merged = fresno.merge(
fresno_page_rows,
on="registration_precinct",
validate="m:1",
how="left",
indicator=True,
)
# check for records that did not match
unmatched = fresno_merged[fresno_merged["_merge"] == "left_only"]
if len(unmatched) != 0:
print(
f"Warning: {len(unmatched)} precincts did not match in the crosswalk data."
)
# display a few examples
debug_output_path = "debug/fresno_unmatched_precincts.csv"
unmatched[["registration_precinct", "_merge"]].to_csv(
debug_output_path, index=False
)
print(f"Unmatched precincts exported to {debug_output_path}")
# drop the indicator column used for debugging
fresno_merged = fresno_merged.drop(columns=["_merge"])
# proceed with the merged data
fresno = fresno_merged
# dissolve on the results_precinct column
fresno = fresno.dissolve("results_precinct")
# reset the index so we can use the column
fresno = fresno.reset_index()
# rename and drop columns
fresno = alter_df(
df=fresno,
county="Fresno",
rename={"results_precinct": "precinct_id"},
drop=[
"OBJECTID",
"AREA_",
"PERIMETER",
"PRCT_",
"PRCT_ID",
"NO_PRCT",
"EIMS_PRCT",
"NO_PRCT_RT",
"NO_PRCT_SU",
"Shape__Are",
"Shape__Len",
"registration_precinct",
],
)
fresno
return (fresno,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## Glenn
""")
return
@app.cell
def _(PROJECTED_CRS, gpd):
_GIS_FP = "inputs/counties/glenn/precincts/Precincts_9_3_2.json"
glenn = gpd.read_file(_GIS_FP).to_crs(PROJECTED_CRS)
glenn = alter_df(
df=glenn,
county="Glenn",
rename={"PREC": "precinct_id"},
drop=[
"OBJECTID",
"P00C58RB_I",
"COUNTY",
"SUP",
"Consolidat",
"Shape_Leng",
"Shape_Le_1",
"Shape__Area",
"Shape__Length",
],
)
glenn.head()
return (glenn,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## Humboldt
""")
return
@app.cell
def _(PROJECTED_CRS, gpd):
_GIS_FP = (
"inputs/counties/humboldt/precincts/precincts17sp_202507111714287445.zip"
)
humboldt = gpd.read_file(_GIS_FP).to_crs(PROJECTED_CRS)
humboldt = alter_df(
df=humboldt,
county="Humboldt",
rename={"PRECINCT": "precinct_name", "Prcnct_Num": "precinct_id"},
drop=["DISTRICT", "ACRES", "POP2010", "Shape_Leng", "Shape_Area"],
)
humboldt.head()
return (humboldt,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## Imperial
""")
return
@app.cell
def _(PROJECTED_CRS, gpd):
_GIS_FP = "inputs/counties/imperial/srprec_025_s25_v01.gpkg.zip"
imperial = gpd.read_file(_GIS_FP).to_crs(PROJECTED_CRS)
imperial = alter_df(
df=imperial,
county="Imperial",
rename={"srprec": "precinct_id"},
drop=["COUNTY"],
)
imperial.head()
return (imperial,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## Inyo (consolidated)
""")
return
@app.cell
def _(PROJECTED_CRS, gpd):
_GIS_FP = "inputs/counties/inyo/precincts/consolidated.zip"
inyo = gpd.read_file(_GIS_FP).to_crs(PROJECTED_CRS)
inyo = alter_df(
df=inyo,
county="Inyo",
rename={"cons_prec": "precinct_id"},
drop=["OBJECTID", "GlobalID", "Shape__Are", "Shape__Len"],
)
inyo.head()
return (inyo,)
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
## Kern
""")
return
@app.cell
def _(pd):
def process_kern_crosswalk_section(
file_path,
usecols,
skiprows,
truncate_after,
columns_to_drop,
rename_mapping,
):
"""
Process a single section of the Kern county crosswalk Excel file.
Parameters:
file_path: Path to the Excel file
usecols: Column range to read (e.g., "B:Q")
skiprows: Number of header rows to skip
truncate_after: Row index to truncate after
columns_to_drop: List of column names to drop
rename_mapping: Dictionary mapping old column names to new ones
pd: pandas module
Returns:
Processed DataFrame with voting_precinct, regular_precinct, and registration columns
"""
df = (
pd.read_excel(
file_path,
usecols=usecols,
skiprows=skiprows,
)
.truncate(after=truncate_after)
.drop(columns=columns_to_drop)
)
df = df.rename(columns=rename_mapping)
df["voting_precinct"] = df["voting_precinct"].ffill()
df_has_voters = df["registration"].notnull()
df = df[df_has_voters].copy()
df["voting_precinct"] = df["voting_precinct"].str.split(" ", expand=True)[
0
]
df = df.reset_index(drop=True)
return df
return (process_kern_crosswalk_section,)
@app.cell
def _(pd, process_kern_crosswalk_section):
# Constants for crosswalk file processing
_CROSSWALK_EXCEL_PATH = (
"inputs/counties/kern/precincts/2025 Statewide Special Election.xls"
)
_CROSSWALK_SKIPROWS = 6 # skip the header rows
# Configuration for left and right sections
_CROSSWALK_SECTIONS = {
"left": {
"usecols": "B:Q", # left half of the data
"truncate_after": 5690, # rows after are relevant to cities in the county
"columns_to_drop": [
"Mail\nBallot ",
"Unnamed: 2",
"Unnamed: 3",
"Unnamed: 4",
"Unnamed: 5",
"Unnamed: 6",
"Unnamed: 8",
"Unnamed: 9",
"Unnamed: 11",
"Unnamed: 12",
"Unnamed: 13",
"Unnamed: 15",
"Ballot \nType",
],
"rename_mapping": {
"\nVoting Precinct": "voting_precinct",
"\nRegular Precinct": "regular_precinct",
"\nRegistration": "registration",
},
},
"right": {
"usecols": "U:AC", # right half of the data
"truncate_after": 5655, # rows after are relevant to cities in the county
"columns_to_drop": [
"Unnamed: 21",
"Mail\nBallot",
"Unnamed: 24",
"Unnamed: 25",
"Unnamed: 26",
"Ballot \nType.1",
],
"rename_mapping": {
"\nVoting Precinct.1": "voting_precinct",
"\nRegular Precinct.1": "regular_precinct",
"\nRegistration.1": "registration",
},
},
}
# the crosswalk file is two columns smashed together
# so we read them into two different data frames to start
kern_sections = [
process_kern_crosswalk_section(
file_path=_CROSSWALK_EXCEL_PATH,
skiprows=_CROSSWALK_SKIPROWS,
**section_config,
)
for section_config in _CROSSWALK_SECTIONS.values()
]
# combine both dataframes to get a single crosswalk dataframe
kern_crosswalk = pd.concat(kern_sections).reset_index(drop=True)
# replace multiple spaces with one in preparation for the merge
kern_crosswalk["regular_precinct"] = kern_crosswalk[
"regular_precinct"
].str.replace(" ", " ")
return (kern_crosswalk,)
@app.cell
def _(PROJECTED_CRS, gpd, kern_crosswalk, pd):
# Constants for shapefile processing
_GIS_PATH = "inputs/counties/kern/precincts/remediainquiryelectionprecinctgeographicfiles/2025 Precincts.shp"
_DROP_COLUMNS = [
"OBJECTID_1",
"OBJECTID",
"Shape_Leng",
"Shape_Le_1",
"Latitude",
"Longitude",
"PrecintID",
"regular_precinct",
]
# read in the shapefile
kern = gpd.read_file(_GIS_PATH).to_crs(PROJECTED_CRS)
# create a key for merging with the crosswalk
kern["regular_precinct"] = (
kern["PrecintID"].astype(str) + " " + kern["Layer"].astype(str)
)
# which includes replacing multiple spaces with a single space
kern["regular_precinct"] = kern["regular_precinct"].str.replace(" +", "")
# merge the two together
kern = pd.merge(
kern, kern_crosswalk, on="regular_precinct", how="inner", validate="m:1"
)
# consolidate registration precincts into voting precincts and add data attributes together
# (we only care about registration)
kern = kern.dissolve(by="voting_precinct", aggfunc="sum").reset_index()