Advertisement
Guest User

Untitled

a guest
Oct 20th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. #importing necessary libraries
  2. import os
  3. import pandas as pd
  4.  
  5. #specifying file location
  6. file = "Resources/election_data.csv"
  7. #reading CSV into pandas dataframe
  8. df = pd.read_csv(file)
  9.  
  10. #note: ONLY works for cleaned datasets where candidate and vote lists are indexed together
  11. #getting list of candidates
  12. candidateNames = df['Candidate'].value_counts().keys().tolist()
  13. #getting list of corresponding votes
  14. voteCounts = df['Candidate'].value_counts().tolist()
  15. #getting total vote count
  16. totalVotes = sum(voteCounts)
  17. #getting list of vote percentages
  18. votePercentages = [x / totalVotes for x in voteCounts]
  19. #getting biggest vote count
  20. mostVotes = max(voteCounts)
  21. #determining election winner
  22. electionWinner = candidateNames[voteCounts.index(mostVotes)]
  23.  
  24. #initializing output list
  25. outputList = []
  26. #filling output list
  27. for x in range(len(candidateNames)):
  28. outputList.append(candidateNames[x] + " received " +
  29. str(voteCounts[x]) + " votes. (" +
  30. str(round(100*(votePercentages[x]), 3)) + "%)")
  31.  
  32.  
  33. #output statements
  34. print("Election Results")
  35. print("-------------------------")
  36. print("Total Votes: " + str(totalVotes))
  37. print("-------------------------")
  38. for x in range(len(outputList)):
  39. print(outputList[x])
  40. print("-------------------------")
  41. print("Winner: " + electionWinner)
  42. print("-------------------------")
  43.  
  44.  
  45. #defining output name/location
  46. output_path = os.path.join(os.getcwd(), "output", "results.txt")
  47.  
  48. #using CSV module to write file
  49. with open(output_path, 'w', newline='') as csvfile:
  50. csvwriter = csv.writer(csvfile, delimiter=',')
  51. csvwriter.writerow(["Election Results"])
  52. csvwriter.writerow(["-------------------------"])
  53. csvwriter.writerow(["Total Votes: " + str(totalVotes)])
  54. csvwriter.writerow(["-------------------------"])
  55. for x in range(len(candidateNames)):
  56. csvwriter.writerow([outputList[x]])
  57. csvwriter.writerow(["-------------------------"])
  58. csvwriter.writerow(["Winner: " + electionWinner])
  59. csvwriter.writerow(["-------------------------"])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement