<jupyter_start><jupyter_text>Ohio ** Redaing File, Some EDA **<jupyter_code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
#import pandas_profiling as pdp
import os
import seaborn as sns
plt.style.use('fivethirtyeight')

% matplotlib inline
OhioCounty = pd.read_csv('1_Ohio.csv')
list(OhioCounty)
Ohio = OhioCounty[['County', 'Voters_StateVoterID', 'Voters_Active', 'Voters_BirthDate', 'Voters_Age', 
                            'Voters_OfficialRegDate', 'Broad Ethnic Groupings', 'Hispanic Country Origin', 
                            'Cable or Dish Television', 'Religions_Description', 'Parties_Description', 'Voters_Gender', 
                            'MaritalStatus_Description', 'Residence_HHParties_Description', 'City', 'Township', 'Village', 
                            'Precinct', 'Latitude', 'Longitude', 'Vote_Frequency', 'earlyvoting_general_2016', 
                            'earlyvoting_general_2014', 'earlyvoting_general_2012', 'earlyvoting_general_2010', 
                            'earlyvoting_general_2008', 'General_2016-11-08', 'General_2014-11-04','General_2012-11-06', 
                            'General_2010-11-02', 'General_2008-11-04', 'General_2006-11-07', 'General_2004-11-02', 
                            'General_2002-11-05', 'General_2000-11-07', 'PRI_BLT_2016-03-15', 'PRI_BLT_2014-05-06', 
                            'PRI_BLT_2012-03-06', 'PRI_BLT_2010-05-04', 'PRI_BLT_2008-03-04', 'PRI_BLT_2006-05-02', 
                            'PRI_BLT_2004-03-02', 'PRI_BLT_2002-05-07', 'PRI_BLT_2000-03-07', 'Home Owner/Renter', 
                            'Net Worth', 'Investor', 'Likely Union Member', 'Business Owner', 'EstimatedIncomeAmount', 
                            'EstimatedIncome', 'Education', 'OccupationIndustry', 'Donates to Conservative Causes', 
                            'Donates to Liberal Causes', 'ReligiousContributorInHome', 'PoliticalContributerInHome', 
                            'Taxes Raise', 'Gun Owner', 
                            'Veteran', 'Affordable Care_Act', 'Church Attendee', 'Gay Marriage', 
                            'Support for Conservative Judges', 'Bush Iraq Policy', 'Gun Control', 
                            'Immigration Loosen Restrictions', 'School Choice', 'CommercialDataLL_Pro_Life', 
                            'CommercialDataLL_Pro_Choice', 'Social Views']]
def DataInspect(dataframe):
    '''Original function (previously called eda) created by <NAME>
       Modified by <NAME> based on his preferences.
       And now, <NAME> modified his version as the follow:'''
    
    print('Dataframe Shape:', dataframe.shape,'\n')
    print('Features Name ---> \n\n', list(dataframe),'\n')
    print('Dataframe Types ---> \n\n', dataframe.dtypes,'\n')    
    print('Missing Values ---> \n\n', dataframe.isnull().sum(),'\n')
    print('Dataframe Describe ---> \n\n', dataframe.describe(include='all'),'\n')
    print('Duplicate Rows:', dataframe.duplicated().sum(),'\n')
        
    print('Unique Values by Variable')
    for item in dataframe:
        print(item,':',dataframe[item].nunique())
DataInspect(Ohio)
Ohio[Ohio.duplicated(keep=False)]
Ohio.drop(12948, inplace = True)
Ohio.drop(13785, inplace = True)<jupyter_output>/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.
/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:2: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy<jupyter_text>Registration **Voter Situation**: 'Active': 1, 'Inactive': 2<jupyter_code>Ohio['Voters_Situation'] = Ohio['Voters_Active'].map(arg={'Active': 1, 'Inactive':0})
Ohio['Voters_RegDate'] = pd.to_datetime(Ohio['Voters_OfficialRegDate'])<jupyter_output>/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.
/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:2: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy<jupyter_text>Geographic Location **CityCity / TownshipTownship / VillageVillage**: 'live': 1, 'NotLive': 0<jupyter_code>Ohio['City'] = Ohio['City'].fillna(0)
Ohio['CityCity'] = [0 if x == 0 else 1 for x in Ohio['City']]
Ohio['Township'] = Ohio['Township'].fillna(0)
Ohio['TownshipTownship'] = [0 if x == 0 else 1 for x in Ohio['Township']]
Ohio['Village'] = Ohio['Village'].fillna(0)
Ohio['VillageVillage'] = [0 if x == 0 else 1 for x in Ohio['Village']]<jupyter_output>/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.
/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:2: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  
/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/p[...]<jupyter_text>Demographic Information **Gender**: 'Male': 1, 'Female':0**Ethnicity**: 'European': 1, 'Likely African-American':2, 'Hispanic and Portuguese':3, 'East and South Asian': 4, 'Other': 5**Hispanic_Country_Origin**: 'Mexico': 1, 'Puerto Rico':2, 'Nicaragua':3, 'Honduras': 4**Marital_Status**: 'Married': 1, 'Non-Traditional':2, 'Single or Unknown':3**Education_Category**: ('Less than HS Diploma - Likely' &'Less than HS Diploma - Ex Like'): 1, ('HS Diploma - Extremely Likely' % 'HS Diploma - Likely'): 2, ('Some College - Likely' &'Some College -Extremely Likely' & 'Vocational Technical Degree - Extremely Likely'): 3, ('Bach Degree - Extremely Likely' & 'Grad Degree - Extremely Likely': 4 & 'Bach Degree - Likely': 4 & 'Grad Degree - Likely'): 4**Worth_Category**: '1-4999': 1, '5000-9999': 2, '10000-24999': 3, '25000-49999': 4, '50000-99999': 5, '100000-249999': 6, '250000-499999': 7, '499999+': 8**Income_Category**: '1,000-14,999': 1, '15,000-24,999':2, '25,000-34,999':3,'35,000-49,999': 4, '50,000-74,999': 5, '75,000-99,999': 6, '100,000-124,999': 7, '125,000-149,999': 8, '150,000-174,999': 9,'175,000-199,999': 10, '200,000-249,999': 11, '250,000 and up': 12**Home_Owner**: 'Likely Homeowner': 1, 'Likely Renter':0**InvestorIndex / Union_Member / Business_Owner / Gun_Owner / Vet **:'Yes': 1**TV**: 'Satellite Dish': 1, 'Cable': 0**Industry** Considere 2 be Dropped * Ohio['Hispanic_Country_Origin'] + Dummies* Ohio['Worth_Category']* Ohio['TV']* Ohio['Industry'] + Dummies<jupyter_code>Ohio['Gender'] = Ohio['Voters_Gender'].map(arg={'M': 1, 'F':0})

Ohio['BirthDate'] = pd.to_datetime(Ohio['Voters_BirthDate'])

Ohio['Ethnicity'] = Ohio['Broad Ethnic Groupings'].map(arg={'European': 1, 'Likely African-American':2, 
                                                            'Hispanic and Portuguese':3, 'East and South Asian': 4, 
                                                            'Other': 5})
pd.get_dummies(Ohio['Ethnicity'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['Ethnicity'])], axis = 1)
Ohio.rename(columns={1.0:'European_D', 2.0:'AfricanAmerican_D', 3.0:'Latino_D', 4.0:'Asian_D', 
                       5.0:'Other_D_Eth'}, inplace=True)

Ohio['Hispanic_Country_Origin'] = Ohio['Hispanic Country Origin'].map(arg={'Mexico': 1, 'Puerto Rico':2, 
                                                            'Nicaragua':3, 'Honduras': 4})
pd.get_dummies(Ohio['Hispanic_Country_Origin'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['Hispanic_Country_Origin'])], axis = 1)
Ohio.rename(columns={1.0:'Mexico_D', 2.0:'PuertoRicon_D', 3.0:'Nicaragua_D', 4.0:'Honduras_D'}, inplace=True)

Ohio['Marital_Status'] = Ohio['MaritalStatus_Description'].map(arg={'Married': 1, 'Non-Traditional':2, 'Single or Unknown':3})

pd.get_dummies(Ohio['Marital_Status'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['Marital_Status'])], axis = 1)
Ohio.rename(columns={1.0:'Married_D', 2.0:'NonTraditional_D', 3.0:'SingleORUnknown_D'}, inplace=True)

Ohio['Education_Category'] = Ohio['Education'].map(arg={'Less than HS Diploma - Likely': 1, 
                                                        'Less than HS Diploma - Ex Like': 1, 
                                                        'HS Diploma - Extremely Likely':2, 
                                                        'HS Diploma - Likely':2, 
                                                        'Some College - Likely': 3,
                                                        'Some College -Extremely Likely': 3, 
                                                        'Vocational Technical Degree - Extremely Likely': 3, 
                                                        'Bach Degree - Extremely Likely': 4,
                                                        'Bach Degree - Likely': 4, 
                                                        'Grad Degree - Extremely Likely': 5, 
                                                        'Grad Degree - Likely': 5, 
                                                        'Unknown': 6})
pd.get_dummies(Ohio['Education_Category'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['Education_Category'])], axis = 1)
Ohio.rename(columns={1.0:'NoHSDiploma_D', 2.0:'HSDiploma_D', 3.0:'SomeCollege_D', 4.0:'BachDegree_D', 
                    5.0:'GradDegree_D', 6.0:'Unknown_D_EduCat'}, inplace=True)

Ohio['Worth_Category'] = Ohio['Net Worth'].map(arg={'$1-4999': 1, '$5000-9999': 2, '$10000-24999': 3, '$25000-49999': 4, 
                                                    '$50000-99999': 5, '$100000-249999': 6, 
                                                    '$250000-499999': 7, '$499999+': 8})
pd.get_dummies(Ohio['Worth_Category'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['Worth_Category'])], axis = 1)
Ohio.rename(columns={1.0:'$1-4999_D', 2.0:'$5000-9999_D', 3.0:'$10000-24999_D', 4.0:'$25000-49999_D', 5.0:'$50000-99999_D', 
                     6.0:'$100000-249999_D', 7.0:'$250000-499999_D', 8.0:'$499999+_D'}, inplace=True)

# Ohio[Ohio['EstimatedIncomeAmount'].notnull() & (Ohio['EstimatedIncomeAmount'] == '$58,888 ')]
# Ohio['EstimatedIncomeAmount'] = Ohio['EstimatedIncomeAmount'].str.replace('$58,888 ', '$58,888')
# Ohio[Ohio['EstimatedIncomeAmount'].notnull() & (Ohio['EstimatedIncomeAmount'] == '$58,888 ')]
# Ohio['Income'] = Ohio['EstimatedIncomeAmount'].str.replace('$', '')
# Ohio['Income'] = Ohio['Income'].astype(float)

Ohio['Income_Category'] = Ohio['EstimatedIncome'].map(arg={'$1,000-$14,999': 1, '$15,000-$24,999':2, '$25,000-$34,999':3, 
                                                           '$35,000-$49,999': 4, '$50,000-$74,999': 5, '$75,000-$99,999': 6, 
                                                           '$100,000-$124,999': 7, '$125,000-$149,999': 8, 
                                                           '$150,000-$174,999': 9, '$175,000-$199,999': 10, 
                                                           '$200,000-$249,999': 11, '$250,000 and up': 12, 
                                                           'Unknown': 13})
pd.get_dummies(Ohio['Income_Category'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['Income_Category'])], axis = 1)
Ohio.rename(columns={1.0:'$1,000-$14,999_D', 2.0:'$15,000-$24,999_D', 3.0:'$25,000-$34,999_D', 4.0:'$35,000-$49,999_D', 
                     5.0:'$50,000-$74,999_D', 6.0:'$75,000-$99,999_D', 7.0:'$100,000-$124,999_D', 
                     8.0:'$125,000-$149,999_D', 9.0:'$150,000-$174,999_D', 10.0:'$175,000-$199,999_D', 
                     11.0:'$200,000-$249,999_D', 12.0:'$250,000 and up_D', 13.0:'Unknown_D_IncCat'}, inplace=True)

Ohio['Home_Owner'] = Ohio['Home Owner/Renter'].map(arg={'Likely Homeowner': 1, 'Likely Renter':0})

Ohio['InvestorIndex'] = [1 if x == 'Yes' else 0 for x in Ohio['Investor']]  

Ohio['Union_Member'] = [1 if x == 'Yes' else 0 for x in Ohio['Likely Union Member']] 

Ohio['Business_Owner'] = [1 if x == 'Yes' else 0 for x in Ohio['Business Owner']] 

Ohio['Gun_Owner'] = [1 if x == 'Yes' else 0 for x in Ohio['Gun Owner']] 

Ohio['Vet'] = [1 if x == 'Yes' else 0 for x in Ohio['Veteran']] 

Ohio['TV'] = Ohio['Cable or Dish Television'].map(arg={'Satellite Dish': 1, 'Cable': 0})

Ohio['Industry'] = Ohio['OccupationIndustry'].map(arg={'Medical': 1, 'Management':2, 'Manufacturing':3, 'Clerical/Office': 4, 
                                                       'Skilled Trades': 5, 'Financial Services': 6, 'Education': 7, 
                                                       'Military': 8, 'Engineering': 9, 'Legal': 10, 'Food Services': 11, 
                                                       'Maintenance Services': 12, 'Computer Professional': 13, 
                                                       'Sales/Marketing': 14, 'Civil Servant': 15, 'Creative Arts': 16, 
                                                       'Scientific': 17, 'Other': 18, 'Unknown': 19})
pd.get_dummies(Ohio['Industry'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['Industry'])], axis = 1)
Ohio.rename(columns={1.0:'Medical_D', 2.0:'Management_D', 3.0:'Manufacturing_D', 4.0:'ClericalOffice_D', 
                     5.0:'SkilledTrades_D', 6.0:'FinancialServices_D', 7.0:'Education_D', 
                     8.0:'Military_D', 9.0:'Engineering_D', 10.0:'Legal_D', 
                     11.0:'FoodServices_D', 12.0:'MaintenanceServices_D', 13.0:'ComputerProfessional_D', 
                     14.0:'SalesMarketing_D', 15.0:'CivilServant_D', 16.0:'Creative Arts_D', 17.0:'Scientific_D', 
                     18.0:'Other_D_Ind', 19.0:'Unknown_D_Ind'}, inplace=True)<jupyter_output>/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  """Entry point for launching an IPython kernel.
/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  This is separate from the ipykernel package so we can avoid doing imports until
/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:7: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = [...]<jupyter_text>Party, Social View & Religion**Religion**: 'Protestant': 1, 'Catholic':2, 'Jewish':3, 'Eastern Orthodox': 4, 'Greek Orthodox': 4, 'Christian': 5, 'Hindu': 6, 'Buddhist': 6, 'Shinto': 6, 'Islamic': 7, 'Lutheran': 8, 'Sikh': 9**Church_Attendee**: 'Yes': 1, 'No':0**Social_Views**: 'Conservative': 1, 'Liberal':0**Donation_Conservatism / Donation_Liberalism**: 'Yes': 1**Party**: 'Republican': 1, 'Democratic':2, 'Libertarian': 3, 'Green': 4, 'Non-Partisan': 5**Party_Home**: 'Republican': 1, 'Democratic':2, 'Independent':3, 'Democratic & Republican': 4, 'Republican & Independent': 5, 'Democratic & Independent': 6,'Democratic & Republican & Independent': 7**Home_PoliticsContribution**: 0 political contributions in home':1, '1 political contribution  in home':2, '2+ political contributions in home':3, **Home_religiousContribution**: 0 religiuos contributions in home':1, '1 religiuos contribution  in home':2, '2+ religious contributions in home':3,  Considere 2 be Dropped * Ohio['Church_Attendee']* Ohio['Social_Views']<jupyter_code>Ohio['Religion'] = Ohio['Religions_Description'].map(arg={'Protestant': 1, 'Catholic':2, 'Jewish':3, 'Christian': 5, 
                                                           'Eastern Orthodox': 4, 'Islamic': 7, 'Hindu': 6, 'Buddhist': 6, 
                                                           'Greek Orthodox': 4, 'Shinto': 6, 'Lutheran': 8, 'Sikh': 9})
pd.get_dummies(Ohio['Religion'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['Religion'])], axis = 1)
Ohio.rename(columns={1.0:'Protestant_D', 2.0:'Catholic_D', 3.0:'Jewish_D', 
                     4.0:'EasternGreekOrthodox_D', 5.0:'Christian_D', 
                     6.0:'Asian_D', 7.0:'Islamic_D', 
                     8.0:'Lutheran_D', 9.0:'Sikh_D'}, inplace=True)

Ohio['Church_Attendee'] = Ohio['Church Attendee'].map(arg={'Yes': 1, 'No':0})

Ohio['Social_Views'] = Ohio['Social Views'].map(arg={'Conservative': 1, 'Liberal':0})

Ohio['Donation_Conservatism'] = [1 if x == 'Yes' else 0 for x in Ohio['Donates to Conservative Causes']]  

Ohio['Donation_Liberalism'] = [1 if x == 'Yes' else 0 for x in Ohio['Donates to Liberal Causes']]  


Ohio['Party'] = Ohio['Parties_Description'].map(arg={'Republican': 1, 'Democratic':2, 'Libertarian': 3, 'Green': 4, 
                                                     'Non-Partisan': 5})
pd.get_dummies(Ohio['Party'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['Party'])], axis = 1)
Ohio.rename(columns={1.0:'PRepublican_D', 2.0:'PDemocratic_D', 3.0:'PLibertarian_D', 4.0:'PGreen_D', 
                     5.0:'PNonPartisan_D'}, inplace=True)

Ohio['Party_Home'] = Ohio['Residence_HHParties_Description'].map(arg={'Republican': 1, 'Democratic':2, 'Independent':3, 
                                                                      'Democratic & Republican': 4,
                                                                      'Republican & Independent': 5,
                                                                      'Democratic & Independent': 6, 
                                                                      'Democratic & Republican & Independent': 7})
pd.get_dummies(Ohio['Party_Home'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['Party_Home'])], axis = 1)
Ohio.rename(columns={1.0:'PHRep_D', 2.0:'PHDem_D', 3.0:'PHInd_D', 
                     4.0:'PHRepDem_D', 
                     5.0:'PHRepInd_D', 
                     6.0:'PHDemInd_D', 
                     7.0:'PHRepDemInd_D'}, inplace=True)

Ohio['Home_PoliticsContribution'] = Ohio['PoliticalContributerInHome'].map(arg={'1 political contribution  in home':2, 
                                                                                '2 political contributions in home':3, 
                                                                                '3 political contributions in home':3, 
                                                                                '4 political contributions in home':3, 
                                                                                '5 political contributions in home':3, 
                                                                                '6 political contributions in home':3, 
                                                                                '7 political contributions in home':3, 
                                                                                '8 political contributions in home':3, 
                                                                                '9 political contributions in home':3})
Ohio['Home_PoliticsContribution'] = Ohio['Home_PoliticsContribution'].fillna(1)

Ohio['Home_ReligiousContribution'] = Ohio['ReligiousContributorInHome'].map(arg={'1 religious contribution  in home':2, 
                                                                                 '2 religious contributions in home':3, 
                                                                                 '3 religious contributions in home':3, 
                                                                                 '4 religious contributions in home':3, 
                                                                                 '5 religious contributions in home':3, 
                                                                                 '6 religious contributions in home':3, 
                                                                                 '7 religious contributions in home':3, 
                                                                                 '8 religious contributions in home':3, 
                                                                                 '9 religious contributions in home':3})
Ohio['Home_ReligiousContribution'] = Ohio['Home_ReligiousContribution'].fillna(1)<jupyter_output><empty_output><jupyter_text>Voting Record **2016_General_EarlyVote**: 'Didn't Vote Early': 1, 'Voted More Than 2 Weeks Before Election':2, 'Voted Less Than 2 Weeks Before Election': 3, **2008 to 2014_General_EarlyVote**: 'Voted Early but Date Unknown': 1, 'Didn't Vote Early': 0**2000 to 2016_General**: 'Y = Voted': 1, 'Didn't Vote': 0**2000 to 2016_Primary**: 'Republican': 1, 'Democratic':2, 'Other':3, 'Did Not Vote': 4<jupyter_code>Ohio['Vote_Freq'] = Ohio['Vote_Frequency']

Ohio['2016_General_EarlyVote'] = Ohio['earlyvoting_general_2016'].map(arg={'Voted Less Than 2 Weeks Before Election': 3, 
                                                                           'Voted More Than 2 Weeks Before Election': 2})
Ohio['2016_General_EarlyVote'] = Ohio['2016_General_EarlyVote'].fillna(1)

Ohio['2014_General_EarlyVote'] = [1 if x == 'Voted Early but Date Unknown' else 0 for x in Ohio['earlyvoting_general_2014']] 
     
Ohio['2012_General_EarlyVote'] = [1 if x == 'Voted Early but Date Unknown' else 0 for x in Ohio['earlyvoting_general_2012']] 

Ohio['2010_General_EarlyVote'] = [1 if x == 'Voted Early but Date Unknown' else 0 for x in Ohio['earlyvoting_general_2010']] 

Ohio['2008_General_EarlyVote'] = [1 if x == 'Voted Early but Date Unknown' else 0 for x in Ohio['earlyvoting_general_2008']] 

Ohio['2016_General'] = [1 if x == 'Y' else 0 for x in Ohio['General_2016-11-08']]  

Ohio['2014_General'] = [1 if x == 'Y' else 0 for x in Ohio['General_2014-11-04']]  

Ohio['2012_General'] = [1 if x == 'Y' else 0 for x in Ohio['General_2012-11-06']]  

Ohio['2010_General'] = [1 if x == 'Y' else 0 for x in Ohio['General_2010-11-02']]  

Ohio['2008_General'] = [1 if x == 'Y' else 0 for x in Ohio['General_2008-11-04']]  

Ohio['2006_General'] = [1 if x == 'Y' else 0 for x in Ohio['General_2006-11-07']]  

Ohio['2004_General'] = [1 if x == 'Y' else 0 for x in Ohio['General_2004-11-02']] 

Ohio['2002_General'] = [1 if x == 'Y' else 0 for x in Ohio['General_2002-11-05']] 

Ohio['2000_General'] = [1 if x == 'Y' else 0 for x in Ohio['General_2000-11-07']]

Ohio['2016_Primary'] = Ohio['PRI_BLT_2016-03-15'].map(arg={'Republican': 1, 'Democratic':2, 'Other':3, 'Did Not Vote': 4})
pd.get_dummies(Ohio['2016_Primary'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['2016_Primary'])], axis = 1)
Ohio.rename(columns={1.0:'P2016REP_D', 2.0:'P2016DEM_D', 3.0:'P2016OTHER_D', 4.0:'P2016NotVote_D'}, inplace=True)

Ohio['2014_Primary'] = Ohio['PRI_BLT_2014-05-06'].map(arg={'Republican': 1, 'Democratic':2, 'Other':3, 'Did Not Vote': 4})
pd.get_dummies(Ohio['2014_Primary'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['2014_Primary'])], axis = 1)
Ohio.rename(columns={1.0:'P2014REP_D', 2.0:'P2014DEM_D', 3.0:'P2014OTHER_D', 4.0:'P2014NotVote_D'}, inplace=True)

Ohio['2012_Primary'] = Ohio['PRI_BLT_2012-03-06'].map(arg={'Republican': 1, 'Democratic':2, 'Other':3, 'Did Not Vote': 4})
pd.get_dummies(Ohio['2012_Primary'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['2012_Primary'])], axis = 1)
Ohio.rename(columns={1.0:'P2012REP_D', 2.0:'P2012DEM_D', 3.0:'P2012OTHER_D', 4.0:'P2012NotVote_D'}, inplace=True)

Ohio['2010_Primary'] = Ohio['PRI_BLT_2010-05-04'].map(arg={'Republican': 1, 'Democratic':2, 'Other':3, 'Did Not Vote': 4})
pd.get_dummies(Ohio['2010_Primary'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['2010_Primary'])], axis = 1)
Ohio.rename(columns={1.0:'P2010REP_D', 2.0:'P2010DEM_D', 3.0:'P2010OTHER_D', 4.0:'P2010NotVote_D'}, inplace=True)

Ohio['2008_Primary'] = Ohio['PRI_BLT_2008-03-04'].map(arg={'Republican': 1, 'Democratic':2, 'Other':3, 'Did Not Vote': 4})
pd.get_dummies(Ohio['2008_Primary'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['2008_Primary'])], axis = 1)
Ohio.rename(columns={1.0:'P2008REP_D', 2.0:'P2008DEM_D', 3.0:'P2008OTHER_D', 4.0:'P2008NotVote_D'}, inplace=True)

Ohio['2006_Primary'] = Ohio['PRI_BLT_2006-05-02'].map(arg={'Republican': 1, 'Democratic':2, 'Other':3, 'Did Not Vote': 4})
pd.get_dummies(Ohio['2006_Primary'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['2006_Primary'])], axis = 1)
Ohio.rename(columns={1.0:'P2006REP_D', 2.0:'P2006DEM_D', 3.0:'P2006OTHER_D', 4.0:'P2006NotVote_D'}, inplace=True)

Ohio['2004_Primary'] = Ohio['PRI_BLT_2004-03-02'].map(arg={'Republican': 1, 'Democratic':2, 'Other':3, 'Did Not Vote': 4})
pd.get_dummies(Ohio['2004_Primary'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['2004_Primary'])], axis = 1)
Ohio.rename(columns={1.0:'P2004REP_D', 2.0:'P2004DEM_D', 3.0:'P2004OTHER_D', 4.0:'P2004NotVote_D'}, inplace=True)

Ohio['2002_Primary'] = Ohio['PRI_BLT_2002-05-07'].map(arg={'Republican': 1, 'Democratic':2, 'Other':3, 'Did Not Vote': 4})
pd.get_dummies(Ohio['2002_Primary'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['2002_Primary'])], axis = 1)
Ohio.rename(columns={1.0:'P2002REP_D', 2.0:'P2002DEM_D', 3.0:'P2002OTHER_D', 4.0:'P2002NotVote_D'}, inplace=True)

Ohio['2000_Primary'] = Ohio['PRI_BLT_2000-03-07'].map(arg={'Republican': 1, 'Democratic':2, 'Other':3, 'Did Not Vote': 4})
pd.get_dummies(Ohio['2000_Primary'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['2000_Primary'])], axis = 1)
Ohio.rename(columns={1.0:'P2000REP_D', 2.0:'P2000DEM_D', 3.0:'P2000OTHER_D', 4.0:'P2000NotVote_D'}, inplace=True)<jupyter_output><empty_output><jupyter_text>Issues **Taxes_Raise / Obama_Care / Gay_Marriage / Support_ConservativeJudges / Bush_Iraq / Gun_Control / Immigration_LoosenRestrictions / School_Choice**: 'Support': 1, 'Oppose':0  **Pro_life / Pro_Choice**: 'Yes': 1 Considere 2 be Dropped * Every Features<jupyter_code>Ohio['Taxes_Raise'] = Ohio['Taxes Raise'].map(arg={'Support': 1, 'Oppose':0})

Ohio['Obama_Care'] = Ohio['Affordable Care_Act'].map(arg={'Support': 1, 'Oppose':0})

Ohio['Gay_Marriage'] = Ohio['Gay Marriage'].map(arg={'Support': 1, 'Oppose':0})

Ohio['Support_ConservativeJudges'] = Ohio['Support for Conservative Judges'].map(arg={'Support': 1, 'Oppose':0})

Ohio['Bush_Iraq'] = Ohio['Bush Iraq Policy'].map(arg={'Support': 1, 'Oppose':0})

Ohio['Gun_Control'] = Ohio['Gun Control'].map(arg={'Support': 1, 'Oppose':0})

Ohio['Immigration_LoosenRestrictions'] = Ohio['Immigration Loosen Restrictions'].map(arg={'Support': 1, 'Oppose':0})

Ohio['School_Choice'] = Ohio['School Choice'].map(arg={'Support': 1, 'Oppose':0})

Ohio['Pro_life'] = Ohio['CommercialDataLL_Pro_Life'].map(arg={'Yes': 1})

Ohio['Pro_Choice'] = Ohio['CommercialDataLL_Pro_Choice'].map(arg={'Yes': 1})<jupyter_output><empty_output><jupyter_text>Drop<jupyter_code>Ohio.drop(['Voters_Active', 'Voters_BirthDate', 'City', 'Township', 'Village',
                            'Voters_OfficialRegDate', 'Broad Ethnic Groupings', 'Hispanic Country Origin', 
                            'Cable or Dish Television', 'Religions_Description', 'Parties_Description', 'Voters_Gender', 
                            'MaritalStatus_Description', 'Residence_HHParties_Description', 'Vote_Frequency',  
                            'earlyvoting_general_2016', 
                            'earlyvoting_general_2014', 'earlyvoting_general_2012', 'earlyvoting_general_2010', 
                            'earlyvoting_general_2008', 'General_2016-11-08', 'General_2014-11-04','General_2012-11-06', 
                            'General_2010-11-02', 'General_2008-11-04', 'General_2006-11-07', 'General_2004-11-02', 
                            'General_2002-11-05', 'General_2000-11-07', 'PRI_BLT_2016-03-15', 'PRI_BLT_2014-05-06', 
                            'PRI_BLT_2012-03-06', 'PRI_BLT_2010-05-04', 'PRI_BLT_2008-03-04', 'PRI_BLT_2006-05-02', 
                            'PRI_BLT_2004-03-02', 'PRI_BLT_2002-05-07', 'PRI_BLT_2000-03-07', 'Home Owner/Renter', 
                            'Investor', 'Likely Union Member', 'Business Owner',  
                            'Education', 'Net Worth', 'EstimatedIncome', 'OccupationIndustry', 'Donates to Conservative Causes', 
                            'Donates to Liberal Causes', 'ReligiousContributorInHome', 'PoliticalContributerInHome', 
                            'Taxes Raise', 'Gun Owner', 
                            'Veteran', 'Affordable Care_Act', 'Church Attendee', 'Gay Marriage', 
                            'Support for Conservative Judges', 'Bush Iraq Policy', 'Gun Control', 
                            'Immigration Loosen Restrictions', 'School Choice', 'CommercialDataLL_Pro_Life', 
                            'CommercialDataLL_Pro_Choice', 'Social Views'], axis=1, inplace=True)
Ohio.drop(['Hispanic_Country_Origin', 'Mexico_D', 'PuertoRicon_D', 'Nicaragua_D', 'Honduras_D', 'TV', 'Industry', 
           'Medical_D', 'Management_D', 'Manufacturing_D', 'ClericalOffice_D', 'SkilledTrades_D', 
           'FinancialServices_D', 'Education_D', 'Military_D', 'Engineering_D', 'Legal_D', 'FoodServices_D', 
           'MaintenanceServices_D', 'ComputerProfessional_D', 'SalesMarketing_D', 'CivilServant_D', 'Creative Arts_D', 
           'Scientific_D', 'Other_D_Ind', 'Unknown_D_Ind'], axis=1, inplace=True)
Ohio.drop(['Worth_Category', '$1-4999_D', '$5000-9999_D', '$10000-24999_D', '$25000-49999_D', '$50000-99999_D', 
           '$100000-249999_D', '$250000-499999_D', '$499999+_D'], axis=1, inplace=True)
Ohio.drop(['Church_Attendee', 'Social_Views'], axis=1, inplace=True)
Ohio.drop(['Taxes_Raise', 'Obama_Care', 'Gay_Marriage', 'Support_ConservativeJudges', 'Bush_Iraq', 
           'Gun_Control', 'Immigration_LoosenRestrictions', 'School_Choice', 'Pro_life', 'Pro_Choice'], axis=1, inplace=True)
Ohio.shape
DataInspect(Ohio)<jupyter_output>Dataframe Shape: (28098, 139) 

Features Name ---> 

 ['County', 'Voters_StateVoterID', 'Voters_Age', 'Precinct', 'Latitude', 'Longitude', 'EstimatedIncomeAmount', 'Voters_Situation', 'Voters_RegDate', 'CityCity', 'TownshipTownship', 'VillageVillage', 'Gender', 'BirthDate', 'Ethnicity', 'European_D', 'AfricanAmerican_D', 'Latino_D', 'Asian_D', 'Other_D_Eth', 'Marital_Status', 'Married_D', 'NonTraditional_D', 'SingleORUnknown_D', 'Education_Category', 'NoHSDiploma_D', 'HSDiploma_D', 'SomeCollege_D', 'BachDegree_D', 'GradDegree_D', 'Unknown_D_EduCat', 'Income_Category', '$1,000-$14,999_D', '$15,000-$24,999_D', '$25,000-$34,999_D', '$35,000-$49,999_D', '$50,000-$74,999_D', '$75,000-$99,999_D', '$100,000-$124,999_D', '$125,000-$149,999_D', '$150,000-$174,999_D', '$175,000-$199,999_D', '$200,000-$249,999_D', '$250,000 and up_D', 'Unknown_D_IncCat', 'Home_Owner', 'InvestorIndex', 'Union_Member', 'Business_Owner', 'Gun_Owner', 'Vet', 'Religion', 'Protestant_D', 'Catholic_D', 'Jewish_D', 'East[...]<jupyter_text>knn ** Adjusting Religion **<jupyter_code>from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
ss = StandardScaler()
knn = KNeighborsClassifier(n_neighbors=4, 
                            weights='uniform')
X_ = Ohio[['Education_Category','Income_Category', 'Latitude', 'Longitude', 'Marital_Status', 'Party', 'Party_Home']]
Xs_ = ss.fit_transform(X_)
print(len(Xs_))

y_ = Ohio['Religion']

Xs_ = pd.DataFrame(Xs_, columns=['Education_Category','Income_Category', 'Latitude', 'Longitude', 'Marital_Status', 'Party', 'Party_Home'])
all_ = pd.DataFrame(Xs_)
all_['Religion'] = y_

all_.dropna(inplace=True)
all_dropped = pd.DataFrame(all_[(all_['Religion'] != 8.0) & (all_['Religion'] != 9.0)])

y_ = all_dropped['Religion']
Xs_ = all_dropped.drop('Religion', axis=1)

scores = cross_val_score(knn, Xs_, y_, cv=5)

print(scores)

knn.fit(Xs_, y_)

knn.predict(Ohio[['Education_Category','Income_Category', 'Latitude', 'Longitude', 'Marital_Status', 'Party', 'Party_Home']])

new_Xs = ss.transform(Ohio[['Education_Category','Income_Category', 'Latitude', 'Longitude', 'Marital_Status', 'Party', 'Party_Home']])

Religion_pred = knn.predict(new_Xs)

Ohio['Religion_pred'] = Religion_pred

len(Religion_pred)
pd.get_dummies(Ohio['Religion_pred'])
Ohio = pd.concat([Ohio, pd.get_dummies(Ohio['Religion_pred'])], axis = 1)
Ohio.rename(columns={1.0:'Protestant_D_RP', 2.0:'Catholic_D_RP', 3.0:'Jewish_D_RP', 
                     4.0:'EasternGreekOrthodox_D_RP', 5.0:'Christian_D_RP', 
                     6.0:'Asian_D_RP', 7.0:'Islamic_D_RP'}, inplace=True)

Ohio['Religion_pred'].value_counts()<jupyter_output><empty_output><jupyter_text>CSV File<jupyter_code>Ohio.to_csv('Ohio_CSV.csv')<jupyter_output><empty_output><jupyter_text>2016 vs 2012 *  based on Ethnicity<jupyter_code>Ohio.Ethnicity.value_counts()
# European: 1,
#'Likely African-American':2,
#'Hispanic and Portuguese':3,
#'East and South Asian': 4,
# 'Others': 5
labels = ['White', 'African-American','Others']

sizes = [22305, 1593, 1364]

colors = ['red', 'lightskyblue', 'pink']

explode = (0.2, 0, 0)

plt.pie(sizes, explode=explode, colors=colors,
        autopct="%1.0f%%", shadow=True, startangle=90)

#patches, texts = plt.pie(sizes, colors=colors,
#       shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.show()
OhioVoted2016 = Ohio.groupby(['2016_General'])
OhioVoted2016.Ethnicity.value_counts()
labels = ['White2016_Voted', 'African-American2016_Voted']

sizes = [16672, 1062]

colors = ['red', 'lightskyblue']

explode = (0, 0)

plt.pie(sizes, explode=explode, colors=colors,
        autopct="%1.1f%%", shadow=True, startangle=90)

#patches, texts = plt.pie(sizes, colors=colors,
#        shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.show()
labels = ['White2016_Voted', 'African-American2016_Voted','Others2016_Voted']

sizes = [16672, 1062, 905]

colors = ['red', 'lightskyblue', 'pink']

explode = (0.2, 0, 0)

plt.pie(sizes, explode=explode, colors=colors,
        autopct="%1.1f%%", shadow=True, startangle=90)

#patches, texts = plt.pie(sizes, colors=colors,
#        shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

#plt.savefig("Ethnicity_Voted2016.png")

plt.show()
OhioVoted2012 = Ohio.groupby(['2012_General'])
OhioVoted2012.Ethnicity.value_counts()
labels = ['White2012_Voted', 'African-American2012_Voted']

sizes = [15313, 1094]

colors = ['red', 'lightskyblue']

explode = (0, 0)

plt.pie(sizes, explode=explode, colors=colors,
        autopct="%1.1f%%", shadow=True, startangle=90)

#patches, texts = plt.pie(sizes, colors=colors,
#        shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.show()
labels = ['White2012_Voted', 'African-American2012_Voted','Others2012_Voted']

sizes = [15313, 1094, 769]

colors = ['red', 'lightskyblue', 'pink']

explode = (0.2, 0, 0)

plt.pie(sizes, explode=explode, colors=colors,
        autopct="%1.1f%%", shadow=True, startangle=90)

#patches, texts = plt.pie(sizes, colors=colors,
#        shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.show()
y_Eu2016 = Ohio[Ohio.Ethnicity == 1]['2016_General'].values
y_Af_Am2016= Ohio[Ohio.Ethnicity == 2]['2016_General'].values
print('P(2016_General | Ethnicity = White):', np.mean(y_Eu2016))
print('P(2016_General | Ethnicity = African-American):', np.mean(y_Af_Am2016))
y_Eu2012 = Ohio[Ohio.Ethnicity == 1]['2012_General'].values
y_Af_Am2012= Ohio[Ohio.Ethnicity == 2]['2012_General'].values
print('P(2012_General | Ethnicity = White):', np.mean(y_Eu2012))
print('P(2012_General | Ethnicity = African-American):', np.mean(y_Af_Am2012))
# https://matplotlib.org/gallery/lines_bars_and_markers/barchart.html#sphx-glr-download-gallery-lines-bars-and-markers-barchart-py
#  '''Original barchart created by link above
#       Modified by <NAME> based on his preferences.'''

Ethnicity2016 = [np.mean(y_Eu2016), np.mean(y_Af_Am2016)]
Ethnicity2012 = [np.mean(y_Eu2012), np.mean(y_Af_Am2012)]

ind = np.arange(len(Ethnicity2016))
width = 0.2

fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/3, Ethnicity2016, width,
                color='IndianRed', label='Ethnicity2016')
rects2 = ax.bar(ind + width/4, Ethnicity2012, width,
                color='SkyBlue', label='Ethnicity2012')

ax.set_ylabel('Probability')
ax.set_title('Probability of Vote - White vs African-American in 2012 & 2016')
ax.set_xticks(ind)
ax.set_xticklabels(('White', 'African-American'))
ax.legend()

def autolabel(rects, xpos='center'):
    """
    Attach a text label above each bar in *rects*, displaying its height.

    *xpos* indicates which side to place the text w.r.t. the center of
    the bar. It can be one of the following {'center', 'right', 'left'}.
    """

    xpos = xpos.lower()  
    ha = {'center': 'center', 'right': 'left', 'left': 'right'}
    offset = {'center': 0.5, 'right': 0.57, 'left': 0.43} 

    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
                '{}'.format(height), ha=ha[xpos], va='bottom')


autolabel(rects1, "left")
autolabel(rects2, "right")

plt.savefig("Ethnicity_PVote.png")

plt.show()<jupyter_output><empty_output><jupyter_text>2016 vs 2012 *  based on Party Affiliation<jupyter_code>Ohio.Party.value_counts()
#'Republican': 1,
#'Democratic':2,
#'Libertarian': 3,
#'Green': 4,
#'Non-Partisan': 5
labels = ['Rep', 'Dem', 'Ind']

sizes = [10234, 7054, 10234]

colors = ['red', 'lightskyblue', 'pink']

explode = (0.1, 0, 0)

plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct="%1.0f%%", shadow=True, startangle=-20)

#patches, texts = plt.pie(sizes, colors=colors,
#        shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.show()
OhioVoted2016 = Ohio.groupby(['2016_General'])
OhioVoted2016.Party.value_counts()
labels = ['Rep2016_Voted', 'Dem2016_Voted', 'Ind2016_Voted']

sizes = [9516, 6124, 5037]

colors = ['red', 'lightskyblue', 'pink']

explode = (0.1, 0, 0)

plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct="%1.1f%%", shadow=True, startangle=-20)

#patches, texts = plt.pie(sizes, colors=colors,
#        shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.show()
OhioVoted2012 = Ohio.groupby(['2012_General'])
OhioVoted2012.Party.value_counts()
labels = ['Rep2012_Voted', 'Dem2012_Voted', 'Ind2012_Voted']

sizes = [9113, 6031, 3895]

colors = ['red', 'lightskyblue', 'pink']

explode = (0.1, 0, 0)

plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct="%1.1f%%", shadow=True, startangle=-20)

#patches, texts = plt.pie(sizes, colors=colors,
#        shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.show()
y_Rep2016 = Ohio[Ohio.Party == 1]['2016_General'].values
y_Dem2016= Ohio[Ohio.Party == 2]['2016_General'].values
print('P(2016_General | Party = Republican):', np.mean(y_Rep2016))
print('P(2016_General | Party = Democratic):', np.mean(y_Dem2016))
y_Rep2012 = Ohio[Ohio.Party == 1]['2012_General'].values
y_Dem2012= Ohio[Ohio.Party == 2]['2012_General'].values
print('P(2012_General | Party = Republican):', np.mean(y_Rep2012))
print('P(2012_General | Party = Democratic):', np.mean(y_Dem2012))
Party2016 = [np.mean(y_Rep2016), np.mean(y_Dem2016)]
Party2012 = [np.mean(y_Rep2012), np.mean(y_Dem2012)]

ind = np.arange(len(Party2016))
width = 0.2

fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/3, Party2016, width,
                color='IndianRed', label='Party2016')
rects2 = ax.bar(ind + width/4, Party2012, width,
                color='SkyBlue', label='Party2012')

ax.set_ylabel('Probability')
ax.set_title('Probability of Vote - Rep vs Dem in 2012 & 2016')
ax.set_xticks(ind)
ax.set_xticklabels(('Rep', 'Dem'))
ax.legend()

def autolabel(rects, xpos='center'):
    """
    Attach a text label above each bar in *rects*, displaying its height.

    *xpos* indicates which side to place the text w.r.t. the center of
    the bar. It can be one of the following {'center', 'right', 'left'}.
    """

    xpos = xpos.lower()  
    ha = {'center': 'center', 'right': 'left', 'left': 'right'}
    offset = {'center': 0.5, 'right': 0.57, 'left': 0.43} 

    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
                '{}'.format(height), ha=ha[xpos], va='bottom')


autolabel(rects1, "left")
autolabel(rects2, "right")

plt.savefig("PartyAffiliation_PVote.png")

plt.show()<jupyter_output><empty_output><jupyter_text>2016 vs 2012 *  based on Education<jupyter_code>Ohio.Education_Category.value_counts()
# Less than HS Diploma: 1,
# HS Diploma: 2,
# Some College: 3,
# Bach Degree and More: 4
labels = ['Non HS Dimploma', 'HS Diploma', 'Some College', 'Graduate+']

sizes = [839, 6424, 3640, 4570]

colors = ['red', 'lightcoral', 'pink', 'lightskyblue']

explode = (0, 0, 0, 0.1)

plt.pie(sizes, explode=explode, colors=colors,
        autopct="%1.0f%%", shadow=True, startangle=80)

#patches, texts = plt.pie(sizes, colors=colors,
#       shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.show()
OhioVoted2016 = Ohio.groupby(['2016_General'])
OhioVoted2016.Education_Category.value_counts()
labels = ['Non HS Dimploma_2016Voted', 'HS Diploma_2016Voted', 'Some College_2016Voted', 'Graduate+_2016Voted']

sizes = [591, 5227, 2830, 3952]

colors = ['red', 'lightcoral', 'pink', 'lightskyblue']

explode = (0, 0, 0, 0.1)

plt.pie(sizes, explode=explode, colors=colors,
        autopct="%1.0f%%", shadow=True, startangle=40)

#patches, texts = plt.pie(sizes, colors=colors,
#      shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.show()
OhioVoted2016 = Ohio.groupby(['2012_General'])
OhioVoted2016.Education_Category.value_counts()
labels = ['Non HS Dimploma_2012Voted', 'HS Diploma_2012Voted', 'Some College_2012Voted', 'Graduate+_2012Voted']

sizes = [489, 5088, 2429, 3889]

colors = ['red', 'lightcoral', 'pink', 'lightskyblue']

explode = (0, 0, 0, 0.1)

plt.pie(sizes, explode=explode, colors=colors,
        autopct="%1.0f%%", shadow=True, startangle=40)

#patches, texts = plt.pie(sizes, colors=colors,
#      shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.savefig("Education_Voted2012.png")

plt.show()
y_Ed12016 = Ohio[Ohio.Education_Category == 1]['2016_General'].values
y_Ed22016 = Ohio[Ohio.Education_Category == 2]['2016_General'].values
y_Ed32016 = Ohio[Ohio.Education_Category == 3]['2016_General'].values
y_Ed42016 = Ohio[Ohio.Education_Category == 4]['2016_General'].values
print('P(2016_General | Education = less than HS Diploma):', np.mean(y_Ed12016))
print('P(2016_General | Education = HS Diploma & Some College):', np.mean(y_Ed22016))
print('P(2016_General | Education = Undergrad):', np.mean(y_Ed32016))
print('P(2016_General | Education = Grad):', np.mean(y_Ed42016))
y_Ed12012 = Ohio[Ohio.Education_Category == 1]['2012_General'].values
y_Ed22012 = Ohio[Ohio.Education_Category == 2]['2012_General'].values
y_Ed32012 = Ohio[Ohio.Education_Category == 3]['2012_General'].values
y_Ed42012 = Ohio[Ohio.Education_Category == 4]['2012_General'].values
print('P(2012_General | Education = less than HS Diploma):', np.mean(y_Ed12012))
print('P(2012_General | Education = HS Diploma & Some College):', np.mean(y_Ed22012))
print('P(2012_General | Education = Undergrad):', np.mean(y_Ed32012))
print('P(2012_General | Education = Grad):', np.mean(y_Ed42012))
Education2016 = [np.mean(y_Ed12016), np.mean(y_Ed22016), np.mean(y_Ed32016), np.mean(y_Ed42016)]
Education2012 = [np.mean(y_Ed12012), np.mean(y_Ed22012), np.mean(y_Ed32012), np.mean(y_Ed42012)]

ind = np.arange(len(Education2016))
width = 0.35

fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, Education2016, width,
                color='IndianRed', label='Education2016')
rects2 = ax.bar(ind + width/2, Education2012, width,
                color='SkyBlue', label='Education2012')

ax.set_ylabel('Probability')
ax.set_title('Probability of Vote - Education category in 2012 & 2016')
ax.set_xticks(ind)
ax.set_xticklabels(('NoDiploma', 'Diploma', 'SomeCollege', 'Graduate'))
ax.legend()

def autolabel(rects, xpos='center'):
    """
    Attach a text label above each bar in *rects*, displaying its height.

    *xpos* indicates which side to place the text w.r.t. the center of
    the bar. It can be one of the following {'center', 'right', 'left'}.
    """

    xpos = xpos.lower()  
    ha = {'center': 'center', 'right': 'left', 'left': 'right'}
    offset = {'center': 0.5, 'right': 0.57, 'left': 0.43}  # x_txt = x + w*off

    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()*offset[xpos], 1.01*height,
                '{}'.format(height), ha=ha[xpos], va='bottom')


#autolabel(rects1, "left")
#autolabel(rects2, "right")

plt.savefig("Education_PVote.png")

plt.show()<jupyter_output><empty_output><jupyter_text>2016 vs 2012  based on Swing Counties: * ASHTABULA* TRUMBULL* PORTAGE* LORAIN* ERIE* SANDUSKY* OTTAWA* WOOD* MONTGOMERY<jupyter_code>OhioCounties2016 = Ohio.groupby(['County'])
OhioCounties2016
Ohio.Ashtabula = Ohio[(Ohio['County'] == 'ASHTABULA')]
Ohio.Trumbull = Ohio[(Ohio['County'] == 'TRUMBULL')]
Ohio.Portage = Ohio[(Ohio['County'] == 'PORTAGE')]
Ohio.Lorain = Ohio[(Ohio['County'] == 'LORAIN')]
Ohio.Erie = Ohio[(Ohio['County'] == 'ERIE')]
Ohio.Sandusky = Ohio[(Ohio['County'] == 'SANDUSKY')]
Ohio.Ottawa = Ohio[(Ohio['County'] == 'OTTAWA')]
Ohio.Wood = Ohio[(Ohio['County'] == 'WOOD')]
Ohio.Montgamery = Ohio[(Ohio['County'] == 'MONTGOMERY')]
frames = [Ohio.Ashtabula, Ohio.Trumbull, Ohio.Portage, Ohio.Lorain, Ohio.Erie, Ohio.Sandusky, 
          Ohio.Ottawa, Ohio.Wood, Ohio.Montgamery]
OhioSwing = pd.concat(frames)
OhioSwing
DataInspect(OhioSwing)
OhioSwingVoted2016 = OhioSwing.groupby(['2016_General'])
OhioSwingVoted2016.Ethnicity.value_counts()
labels = ['White2016_Voted', 'African-American2016_Voted','Others2016_Voted']

sizes = [2026, 172, 167]

colors = ['red', 'lightskyblue', 'pink']

explode = (0.2, 0, 0)

plt.pie(sizes, explode=explode, colors=colors,
        autopct="%1.1f%%", shadow=True, startangle=90)

#patches, texts = plt.pie(sizes, colors=colors,
#        shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.show()
OhioSwingVoted2012 = OhioSwing.groupby(['2012_General'])
OhioSwingVoted2012.Ethnicity.value_counts()
labels = ['White2012_Voted', 'African-American2012_Voted','Others2012_Voted']

sizes = [1874, 164, 149]

colors = ['red', 'lightskyblue', 'pink']

explode = (0.2, 0, 0)

plt.pie(sizes, explode=explode, colors=colors,
        autopct="%1.1f%%", shadow=True, startangle=90)

#patches, texts = plt.pie(sizes, colors=colors,
#        shadow=True, startangle=90)

plt.legend(patches, labels, loc="best")

plt.axis("equal")

plt.tight_layout()

plt.show()<jupyter_output><empty_output><jupyter_text>More Analysis<jupyter_code>DataInspect(Ohio)
list(Ohio)
Ohio.tail()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16710609683814662, 'fraction_numerical': 0.070778915527214, 'mean_word_length': 3.5493258949325894, 'pattern_counts': {'":': 0, '<': 60, '<?xml version=': 0, '>': 65, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 122, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '376001', 'license': 'MIT', 'n_tokens_mistral': 20014, 'n_tokens_neox': 16661, 'n_words': 3320, 'path': 'Jupyter/OhioGW_Rev0_20180711.ipynb', 'repo_name': 'aaarash/US_Elections_President_Model_Ohio_4GW', 'size': '48960'}