Guest User

Untitled

a guest
Nov 5th, 2020
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4.  
  5. data = pd.read_csv("president_county_candidate.csv")
  6.  
  7. def GetFirstDigit(num) -> int:
  8.     first_digit = num
  9.     while (first_digit >= 10):
  10.         first_digit = first_digit // 10
  11.     return (1 if first_digit == 0 else first_digit)
  12.  
  13. biden = [0] * 10
  14. trump = [0] * 10
  15.  
  16. # get occurance data
  17. for index, row in data.iterrows():
  18.     digit = GetFirstDigit(data['votes'][index])
  19.     if (data['candidate'][index] == 'Joe Biden'):
  20.         biden[digit] += 1
  21.     elif (data['candidate'][index] == 'Donald Trump'):
  22.         trump[digit] += 1
  23.  
  24. num_counties = len(data.county.unique())    # should be 3007, but we get the value from data anyway
  25. if (num_counties != 3007): # bit of a sanity check
  26.     print('Incomplete statistics')
  27.  
  28. # get occurance data as measure of probability
  29. for index in range(10):
  30.     biden[index] = biden[index] / num_counties
  31.     trump[index] = trump[index] / num_counties
  32.  
  33.  
  34. fig, ax = plt.subplots()
  35. plt.xlim((1, 9))
  36.  
  37. benford = [0, .301, .176, .125, .097, .079, .067, .058, .051, 0.046]
  38.  
  39. ax.plot(biden, label='Biden', color='b')
  40. ax.plot(trump, label='Trump', color='r')
  41. ax.plot(benford, label='True Benford', color='y')
  42.  
  43. ax.set_ylabel('Probability of Occurance')
  44. ax.set_xlabel('Most Significant Integer')
  45. ax.set_title('2020 Votes for Major Candidates vs Benford\'s Law')
  46. ax.legend()
  47.  
  48. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment