Reputation: 39
I am trying to go through a list that has been imported from a csv file and find the number of times a candidate has been voted for. I am writing this in python and I am not sure if I should create a dictionary and do an index search or create a loop that will give me a count of the name?
Sample Data:
Voter ID,County,Candidate
12864552,Marsh,Khan
17444633,Marsh,Correy
19330107,Marsh,Khan
19865775,Queen,Khan
11927875,Marsh,Khan
19014606,Marsh,Li
17775191,Queen,Correy
14003692,Marsh,Khan
Upvotes: 1
Views: 1299
Reputation: 44555
From the standard library:
Given
A sample file test.txt
:
Voter ID,County,Candidate
12864552,Marsh,Khan
17444633,Marsh,Correy
19330107,Marsh,Khan
19865775,Queen,Khan
11927875,Marsh,Khan
19014606,Marsh,Li
17775191,Queen,Correy
14003692,Marsh,Khan
12864552,Marsh,Khan
17444633,Marsh,Correy
19330107,Marsh,Khan
19865775,Queen,Khan
11927875,Marsh,Khan
19014606,Marsh,Li
17775191,Queen,Correy
14003692,Marsh,Khan
Code
import collections as ct
filepath = "test.txt"
with open(filepath) as f:
votes = ct.Counter()
header = next(f)
for line in f:
candidate = line.split(",")[-1].strip()
votes[candidate] += 1
Alternatively
import csv
import collections as ct
filepath = "test.txt"
with open(filepath) as f:
votes = ct.Counter()
reader = csv.reader(f)
next(reader)
for line in reader:
candidate = line[-1]
votes[candidate] += 1
Demo
votes
# Counter({'Khan': 10, 'Correy': 4, 'Li': 2})
votes.most_common(1)
# [('Khan', 10)]
See also docs on collections.Counter
and csv
modules.
Upvotes: 0
Reputation: 71610
Or can do pandas
, pandas.DataFrame.groupby
, then do as_index=False
inside, then do count
for counting:
import pandas as pd
df=pd.read_csv(filename)
print(df.groupby(['Candidate','County'],as_index=False).count())
Upvotes: 1
Reputation: 34677
If you don't want to use pandas, you may also use a Counter, from the collections tree. A sample of using this class is below. If you would like something specific to your problem, edit your question to post what you've tried and I'll edit this response to help you.
c = Counter('abcaba')
c['a'] += 1 # increment an existing value
c.clear() # clear the counter -- all values are 0 and you can start again
c['hd1'] # should be 1
c['hd1'] = c['hd1']+1
c['hd1'] # should be 2
Upvotes: 1
Reputation: 649
First install python-pandas with
pip install pandas
Then you can use the following code for getting the candidates count county-wise.
import pandas as pd
df = pd.read_csv('<path_to_csv.file>')
df.groupby(['Candidate', 'County']).count()
Upvotes: 0