Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #importing necessary libraries
- import os
- import pandas as pd
- #specifying file location
- file = "Resources/election_data.csv"
- #reading CSV into pandas dataframe
- df = pd.read_csv(file)
- #note: ONLY works for cleaned datasets where candidate and vote lists are indexed together
- #getting list of candidates
- candidateNames = df['Candidate'].value_counts().keys().tolist()
- #getting list of corresponding votes
- voteCounts = df['Candidate'].value_counts().tolist()
- #getting total vote count
- totalVotes = sum(voteCounts)
- #getting list of vote percentages
- votePercentages = [x / totalVotes for x in voteCounts]
- #getting biggest vote count
- mostVotes = max(voteCounts)
- #determining election winner
- electionWinner = candidateNames[voteCounts.index(mostVotes)]
- #initializing output list
- outputList = []
- #filling output list
- for x in range(len(candidateNames)):
- outputList.append(candidateNames[x] + " received " +
- str(voteCounts[x]) + " votes. (" +
- str(round(100*(votePercentages[x]), 3)) + "%)")
- #output statements
- print("Election Results")
- print("-------------------------")
- print("Total Votes: " + str(totalVotes))
- print("-------------------------")
- for x in range(len(outputList)):
- print(outputList[x])
- print("-------------------------")
- print("Winner: " + electionWinner)
- print("-------------------------")
- #defining output name/location
- output_path = os.path.join(os.getcwd(), "output", "results.txt")
- #using CSV module to write file
- with open(output_path, 'w', newline='') as csvfile:
- csvwriter = csv.writer(csvfile, delimiter=',')
- csvwriter.writerow(["Election Results"])
- csvwriter.writerow(["-------------------------"])
- csvwriter.writerow(["Total Votes: " + str(totalVotes)])
- csvwriter.writerow(["-------------------------"])
- for x in range(len(candidateNames)):
- csvwriter.writerow([outputList[x]])
- csvwriter.writerow(["-------------------------"])
- csvwriter.writerow(["Winner: " + electionWinner])
- csvwriter.writerow(["-------------------------"])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement