-
Notifications
You must be signed in to change notification settings - Fork 0
/
vt2020.py
634 lines (483 loc) · 19.2 KB
/
vt2020.py
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
import pandas as pd
import electioncleaner as EC
DataFrame = pd.core.frame.DataFrame
Series = pd.core.series.Series
def load_file(file: str) -> DataFrame:
data = pd.read_excel(file)
# We do not need Total votes
data = data.drop('Total Votes', axis=1)
data = data.melt(id_vars=['Town', 'Rep District'],
var_name='Candidate', value_name='Votes')
name = file[4:-51]
# Drop Write-In if votes == 0
data = data[
~((data['Candidate'].str.upper().str.contains('\(WRITE-IN\)')) &
(data['Votes'] == 0))
].reset_index(drop=True)
data['File'] = name
return data
def load_file2(file: str) -> DataFrame:
all_sheets = pd.read_excel(file, sheet_name=None)
data = pd.DataFrame()
for sheet in all_sheets.values():
# Remove vote totals
sheet = sheet.drop(columns=sheet.columns[-2:], axis=1)
# Remove vote types
sheet = sheet.drop(sheet.tail(4).index)
title = sheet.columns[0]
sheet.columns = ['Candidate', 'Party']
office, magnitude = title.split(' || ')
sheet['Magnitude'] = magnitude[16:]
# Make file field that matches other format
file2 = 'StateWide' if file == 'raw2/state.xlsx' else file[5:-5].capitalize()
if office.startswith('STATE SENATOR'):
office = office[15:]
elif office.startswith('STATE REPRESENTATIVE'):
office = office[22:]
elif file2 == 'County':
if office == 'ADDISON':
office = 'ADDISON_HIGH BAILIFF'
else:
office = office + '_' + office
sheet['File'] = file2 + '_' + office
data = data.append(sheet)
return data
def load_files() -> DataFrame:
data = pd.DataFrame()
for file in EC.simple_walk():
print(f'*Reading file raw/{file}...')
file_data = load_file(f'raw/{file}')
data = data.append(file_data)
print(f'Read file raw/{file}...')
data = data.reset_index(drop=True)
return data
def load_files2() -> DataFrame:
data = pd.DataFrame()
for file in EC.simple_walk(raw_folder='raw2'):
print(f'*Reading file raw2/{file}...')
file_data = load_file2(f'raw2/{file}')
data = data.append(file_data)
print(f'Read file raw2/{file}...')
# Standardize for the sake of being able to merge
data['Candidate'] = data['Candidate'].replace({
'AMOS COLBY \(Write-in\)': 'AMOS COLBY(Write-In)',
}, regex=True)
data = data.reset_index(drop=True)
return data
def load_all_data(prepare_pickle=True) -> DataFrame:
if prepare_pickle:
data1 = load_files()
data2 = load_files2()
data = data1.merge(data2, how='outer', on=['Candidate', 'File'])
data['Party'] = data['Party'].fillna('') # Only such cases are writeins
data.to_pickle('raw_VT20.pkl')
data = pd.read_pickle('raw_VT20.pkl')
return data
def make_state(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `state`...')
# State is Vermont by definition
data = EC.state.add_state_codes(data, state='Vermont')
print('Parsed VT20 `state`.')
return data
def make_precinct(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `precinct`...')
# Data is pulled straight from `Town`.
data['temp_precinct'] = data['Town'].astype(str).str.strip().str.upper()
# Still need to add - FLOAT were appropriate
print('Partially parsed VT20 `precinct` (1/2).')
return data
def make_office(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `office`...')
# Data is pulled from `File`
data['office'] = data['File']
# Standardize names
standard_names = {
r'County.*': 'COUNTY HIGH BAILIFF', # All such elections are High Bailiff
r'Federal_REPRESENTATIVE.*': 'US HOUSE',
r'Federal_US PRESIDENT.*': 'US PRESIDENT',
r'House_.*': 'STATE HOUSE',
r'Senate_.*': 'STATE SENATE',
r'StateWide_': '', # Rest of name is already standardized
}
data['office'] = data['office'].replace(standard_names, regex=True)
print('Parsed VT20 `office`.')
return data
def make_party_detailed(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `party_detailed...`')
data['party_detailed'] = data['Party'].replace({
'DEMOCRATIC': 'DEMOCRAT',
'DEM/REP': 'DEMOCRAT-REPUBLICAN',
'REP/DEM': 'REPUBLICAN-DEMOCRAT',
'PROG/DEM': 'PROGRESSIVE-DEMOCRAT',
'DEM/PROG': 'DEMOCRAT-PROGRESSIVE',
}, regex=True)
print('Parsed VT20 `party_detailed`.')
return data
def make_party_simplified(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `party_simplified...`')
same = {
'DEMOCRAT',
'REPUBLICAN',
'LIBERTARIAN',
''
}
data['party_simplified'] = data['party_detailed'].where(
data['party_detailed'].isin(same),
'OTHER'
)
print('Parsed VT20 `party_simplified`.')
return data
def make_mode(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `mode`...')
# Mode is consistently 'TOTAL'
data['mode'] = 'TOTAL'
print('Parsed VT20 `mode`.')
return data
def make_votes(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `votes...`')
# Data is pulled straight from `Votes`
data['votes'] = pd.to_numeric(data['Votes'], errors='raise')
print('Parsed VT20 `votes`.')
return data
def make_county_name(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `county_name`...')
# Data is pulled from `File`. We use the County elections to figure out which town
# belongs to each county. WE cannot use Rep District as a few Rep District contain
# 2 or more counties. We also take advantage of the fact each town name is unique
county = data[data['File'].str.contains('County')][['Town', 'File']].drop_duplicates()
county = EC.split_column(county, 'File', '.*_(?P<County>.*)_.*')
county_map = county[['Town', 'County']].set_index('Town').to_dict()['County']
data['county_name'] = data['Town'].replace(county_map)
print('Parsed VT20 `county_name`.')
return data
def make_county_fips(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `county_fips`...')
# Use recently obtained `county_name` field and list of county fips codes
data['county_fips'] = EC.county_fips.parse_fips_from_name(data)
print('Parsed VT20 `county_fips`.')
return data
def make_jurisdiction_name(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `jurisdiction_name`...')
# `jurisdiction_name` is the same as `precinct` for Vermont, so use that
data['jurisdiction_name'] = data['temp_precinct']
print('Parsed VT20 `jurisdiction_name`.')
return data
def make_jurisdiction_fips(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `jurisdiction_fips`...')
additional = {
# From fips file.
"SAINT JOHNSBURY": 5000562200,
"SAINT GEORGE": 5000762050,
# https://en.wikipedia.org/wiki/St._Albans_(city),_Vermont
"SAINT ALBANS CITY": 5001161675,
# https://en.wikipedia.org/wiki/St._Albans_(town),_Vermont
"SAINT ALBANS TOWN": 5001161750,
# https://en.wikipedia.org/wiki/Newport_(city),_Vermont
"NEWPORT CITY": 5001948850,
# https://en.wikipedia.org/wiki/Newport_(town),_Vermont
"NEWPORT TOWN": 5001948925,
# https://en.wikipedia.org/wiki/Rutland_(city),_Vermont
"RUTLAND CITY": 5002161225,
# https://en.wikipedia.org/wiki/Rutland_(town),_Vermont
"RUTLAND TOWN": 5002161300,
# https://en.wikipedia.org/wiki/Barre_(city),_Vermont
"BARRE CITY": 5002303175,
# https://en.wikipedia.org/wiki/Barre_(town),_Vermont
"BARRE TOWN": 5002303250,
}
# Use recently obtained `jurisdiction_name` field and list of county fips codes
data['jurisdiction_fips'] = EC.jurisdiction_fips.parse_fips_from_name(data,
additional=additional)
print('Parsed VT20 `jurisdiction_fips`.')
return data
def make_candidate(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `candidate...`')
# Data is pulled from Candidate and uppercased
data['temp_candidate'] = data['Candidate'].str.upper().str.strip()
# First, remove any extraneous whitespace/characters
data['temp_candidate'] = data['temp_candidate'].str.strip().replace({
r' ( )+': ' ',
r' - ': ' AND ',
r'\.': '',
r',': '',
r'&': 'AND',
}, regex=True)
# Standardize some candidates
data['temp_candidate'] = data['temp_candidate'].replace({
r'SPOILED BALLOTS': 'OVERVOTES',
r'SPOILED VOTES': 'OVERVOTES',
r'BLANK VOTES': 'UNDERVOTES',
r'BLANK/FICTIOUS': 'SCATTER',
r'OVAL FILLED/BLANK': 'SCATTER',
r'BLANK/FICTITIOUS': 'SCATTER',
r'TOTAL WRITE-INS?': 'WRITEIN',
r'CHRIS O;GRADY': "CHRIS O'GRADY",
r'LAURA CHA\[PMAN': 'LAURA CHAPMAN',
r'\[AUL MEACHAM': 'PAUL MEACHAM',
r'SMITTY \?\?\?': 'SMITTY',
r'\"ELISCA STEPHANIC\"': 'ELISCA STEPHANIC',
r'PETER JR MARTIN': 'PETER J R MARTIN',
r'WOODMAN \"WOODY\" H PAGE': 'WOODMAN H "WOODY" PAGE',
}, regex=True)
# Replace / with AND. We do this now so that it doesn't conflict with BLANK/FICTIOUS etc
data['temp_candidate'] = data['temp_candidate'].str.strip().replace({
r'/ ?': ' AND ',
}, regex=True)
# For non writein US President, remove the Vicepresident
data['temp_candidate'] = data['temp_candidate'].mask(
(data['office']=='US PRESIDENT') & (~data['temp_candidate'].str.contains('WRITE-IN')),
data['temp_candidate'].replace({
' AND.*': '',
}, regex=True)
)
# We will remove Writein later
print('Partially parsed VT20 `candidate` (1/2).')
return data
def make_district(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `district`...')
# Data is pulled from District
data['district'] = data['Rep District']
# removing this, as overwriting the district field for statewide offices leads to quasi duplicate rows because there are
# multiple rows per township in the raw data that are differentiated by the district field.
# Except statewide/federal races, whose district must be STATEWIDE
statewide = {
'US PRESIDENT',
'ATTORNEY GENERAL',
'AUDITOR OF ACCOUNTS',
'GOVERNOR',
'LIEUTENANT GOVERNOR',
'SECRETARY OF STATE',
'STATE TREASURER',
}
data['district'] = data['district'].mask(
data['office'].isin(statewide),
'STATEWIDE',
)
data['district'] = data['district'].mask(data['office'].str.contains('COUNTY'), "")
data['district'] = data['district'].mask(data['office']=='US HOUSE', "000")
print('Parsed VT20 `district`.')
return data
def make_magnitude(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `magnitude`...')
data['magnitude'] = data['Magnitude'].replace({
'ONE': 1,
'TWO': 2,
'THREE': 3,
'SIX': 6,
})
# We still have a few NaNs, we get rid of the trivial 1s
trivial_magnitude_one = {
'US PRESIDENT',
'US HOUSE',
'ATTORNEY GENERAL',
'AUDITOR OF ACCOUNTS',
'GOVERNOR',
'LIEUTENANT GOVERNOR',
'SECRETARY OF STATE',
'STATE TREASURER',
'COUNTY HIGH BAILIFF'
}
data['magnitude'] = data['magnitude'].mask(
data['office'].isin(trivial_magnitude_one),
1
)
# For State House, each office, district either has magnitude one number or NaN
# We replace the NaNs with the proper number, taking advantage n < NaN for all numbers n
house = data[data['office']=='STATE HOUSE'][['magnitude', 'district']]
house = house.drop_duplicates().sort_values(['district', 'magnitude'])
house['magnitude'] = house['magnitude'].ffill()
house = house.drop_duplicates()
house_dict = house.set_index('district').to_dict()['magnitude']
data['magnitude'] = data['magnitude'].mask(
data['office'] == 'STATE HOUSE',
data['district'].replace(house_dict)
)
# State Senate is the same. However, we also need the name of the town (precinct) as for a
# few districts, it is the case that different towns elect different number of state senators
senate = data[data['office']=='STATE SENATE'][['magnitude', 'district', 'temp_precinct']]
senate = senate.drop_duplicates().sort_values(['district', 'temp_precinct', 'magnitude'])
senate['magnitude'] = senate['magnitude'].ffill()
senate = senate.drop_duplicates()
senate_dict = senate.set_index(['district', 'temp_precinct']).to_dict()['magnitude']
senate_dict = {(key[0] + '_' + key[1]): value for key, value in senate_dict.items()}
data['District_precinct'] = data['district'] + '_' + data['temp_precinct']
data['magnitude'] = data['magnitude'].mask(
data['office'] == 'STATE SENATE',
data['District_precinct'].replace(senate_dict)
)
data['magnitude'] = data['magnitude'].astype(int)
# Now that we no longer need precinct, we can update the floating precincts
# These happen as a few towns physically located in one county vote for state senator in a
# neighboring county
# We use the districts to match, as they are unique
# floating = {
# # Addison
# # Huntington is in Chittenden and votes for Addison senator
# 'WAS-CHI_HUNTINGTON',
# # Bennington
# # Wilmington is in Windham and votes for Bennington senator
# 'WDH-6_WILMINGTON',
# # Caledonia
# # Several towns are in Orange and vote for Caledonia senator
# 'ORA-2_BRADFORD',
# 'ORA-2_FAIRLEE',
# 'ORA-2_WEST FAIRLEE',
# 'ORA-CAL_NEWBURY',
# 'ORA-CAL_TOPSHAM',
# 'ORA-1_ORANGE',
# # Chittenden
# # -
# # Essex-Orleans
# # Wolcott is in Lamoille and votes for Essex-Orleans senator
# 'LAM-2_WOLCOTT',
# 'FRA-7_MONTGOMERY',
# 'FRA-5_RICHFORD',
# # Franklin
# # Alburgh is in Grand Isle and votes for Franklin senator
# 'GI-CHI_ALBURGH',
# # Grand Isle
# # Colchester is in Chittenden and votes for Grand Isle senator
# 'CHI-9-1_COLCHESTER',
# 'CHI-9-2_COLCHESTER',
# # Lamoille
# # -
# # Orange
# # -
# # Rutland
# # -
# # Washington
# # -
# # Windham
# # -
# # Windsor
# # Londonderry is in Windham and votes for Windsor senator
# 'WDH-BEN-WDR_LONDONDERRY',
# }
# data['precinct'] = data['temp_precinct'].mask(
# (data['office'] == 'STATE SENATE') & (data['District_precinct'].isin(floating)),
# data['temp_precinct'] + ' - FLOAT'
# )
print('Parsed VT20 `magnitude`.')
return data
def make_dataverse(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `dataverse`...')
data['dataverse'] = EC.dataverse.parse_dataverse_from_office(
data['office'],
state={
'STATE HOUSE',
'STATE SENATE',
'ATTORNEY GENERAL',
'AUDITOR OF ACCOUNTS',
'GOVERNOR',
'LIEUTENANT GOVERNOR',
'SECRETARY OF STATE',
'STATE TREASURER'
},)
print('Parsed VT20 `dataverse`.')
return data
def make_year(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `year`...')
# Year is 2020 by definition
data['year'] = 2020
print('Parsed VT20 `year`.')
return data
def make_stage(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `stage`...')
# Stage is consistently general for current data
data['stage'] = 'GEN'
print('Parsed VT20 `stage`.')
return data
def make_special(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `special`...')
# # Special is consistently false for current data
data['special'] = EC.r_bool(False)
print('Parsed VT20 `special`.')
return data
def make_writein(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `writein`...')
# We parse this from Candidate
data['writein'] = EC.series_r_bool(data['temp_candidate'].str.contains('WRITE-?IN'))
data['candidate'] = data['temp_candidate'].replace({
'\(WRITE-IN\)': ''
}, regex=True).str.strip()
print('Parsed VT20 `candidate` (2/2).')
print('Parsed VT20 `writein`.')
return data
def make_state_po(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `state_po`...')
# Already parsed
print('Parsed VT20 `state_po`.')
return data
def make_state_fips(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `state_fips`...')
# Already parsed
print('Parsed VT20 `state_fips`.')
return data
def make_state_cen(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `state_cen`...')
# Already parsed
print('Parsed VT20 `state_cen`.')
return data
def make_state_ic(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `state_ic`...')
# Already parsed
print('Parsed VT20 `state_ic`.')
return data
def make_date(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `date...`')
# Vermont had one date for all elections
data['date'] = '2020-11-03'
print('*Parsed VT20 `date`.')
return data
def make_readme_check(data: DataFrame) -> DataFrame:
print('*Parsing VT20 `readme_check...`')
# # Floating precincts
# data['readme_check'] = EC.series_r_bool(
# data['precinct'].str.contains(' - FLOAT')
# )
data['readme_check'] = 'FALSE'
print('Parsed VT20 `readme_check`.')
return data
if __name__ == '__main__':
print("Parsing raw data for Vermont.")
raw_data = load_all_data(prepare_pickle=True)
print("Parsed VT20 raw data for Vermont.")
EC.check_original_dataset(
raw_data,
expected_columns={'Town', 'Rep District', 'Candidate', 'Votes', 'File', 'Magnitude',
'Party'},
)
data = raw_data.copy()
# Parse needed details for standard form
data = make_state(data)
data = make_precinct(data)
data = make_office(data)
data = make_party_detailed(data)
data = make_party_simplified(data)
data = make_mode(data)
data = make_votes(data)
data = make_county_name(data)
data = make_county_fips(data)
data = make_jurisdiction_name(data)
data = make_jurisdiction_fips(data)
data = make_candidate(data)
data = make_district(data)
data = make_magnitude(data)
data = make_dataverse(data)
data = make_year(data)
data = make_stage(data)
data = make_special(data)
data = make_writein(data)
data = make_state_po(data)
data = make_state_fips(data)
data = make_state_cen(data)
data = make_state_ic(data)
data = make_date(data)
data = make_readme_check(data)
# making new precinct field
data['precinct'] = data['temp_precinct'] + '_' + data['Rep District']
data = EC.select_cleaned_dataset_columns(data, False)
data = EC.sort_cleaned_dataset(data)
EC.check_cleaned_dataset(data, expected_counties=14, expected_jurisdictions=246)
EC.inspect_cleaned_dataset(data)
EC.save_cleaned_dataset(data, '2020-vt-precinct-general.csv')