Last active
November 11, 2024 21:57
-
-
Save CaptainStabs/fa36894bdf9bee8d0ad06088720d4d71 to your computer and use it in GitHub Desktop.
Separates Michigan voter data into democratic, republican, and independent votes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import pandas as pd | |
folder = './elections/' | |
for file in os.listdir(folder): | |
df = pd.read_csv(folder + file, sep='\t', skipfooter=1) | |
df['OfficeDescription'].loc[1] | |
df = df.loc[df['OfficeDescription'] == 'ELECTORS OF PRESIDENT AND VICE-PRESIDENT OF THE UNITED STATES 4 YEAR TERM (1) POSITION'] | |
def g(df): | |
pivoted = df.pivot_table(values='CandidateVotes', index='CountyName', columns='PartyDescription', aggfunc='sum')#+ | |
pivoted.columns = [col.replace(' ', '_') for col in pivoted.columns] | |
return pivoted | |
result = g(df.copy()) | |
df = result | |
columns_to_sum = df.columns[~df.columns.isin(['REPUBLICAN', 'DEMOCRATIC', 'CountyName'])] | |
df['Independents'] = df[columns_to_sum].sum(axis=1) | |
df.drop(['GREEN', 'LIBERTARIAN', 'NATURAL_LAW', 'NO_PARTY_AFFILIATION', 'U.S._TAXPAYERS'], axis=1, inplace=True) | |
df.to_csv(file.replace('.txt', '') + '_CLEANED.csv', index=False) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment