Python 计算候选人被投票支持的次数
我试图通过一个从csv文件导入的列表来查找候选人的投票次数。我是用python写这篇文章的,我不确定是应该创建一个字典并进行索引搜索,还是创建一个循环来计算名称Python 计算候选人被投票支持的次数,python,dictionary,Python,Dictionary,我试图通过一个从csv文件导入的列表来查找候选人的投票次数。我是用python写这篇文章的,我不确定是应该创建一个字典并进行索引搜索,还是创建一个循环来计算名称 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,
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
首先使用安装python
pip install pandas
然后,您可以使用下面的代码来获得各个县的候选人数
import pandas as pd
df = pd.read_csv('<path_to_csv.file>')
df.groupby(['Candidate', 'County']).count()
将熊猫作为pd导入
df=pd.read_csv(“”)
df.groupby(['Candidate','County']).count()
如果您不想使用熊猫,您也可以使用熊猫。下面是使用此类的示例。如果您想了解您的问题的具体内容,请编辑您的问题以发布您尝试过的内容,我将编辑此回复以帮助您
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
或者可以执行
pandas
,pandas.DataFrame.groupby
,然后在内部执行as_index=False
,然后执行count
进行计数:
import pandas as pd
df=pd.read_csv(filename)
print(df.groupby(['Candidate','County'],as_index=False).count())
从标准库: 给定的 示例文件
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
代码
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
或者
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
演示
votes
# Counter({'Khan': 10, 'Correy': 4, 'Li': 2})
votes.most_common(1)
# [('Khan', 10)]
另请参见
集合。计数器和模块 熊猫将是你在这里的朋友import pandas as pd
,后跟pd.read_csv('filename.csv')。Candidate.value_counts()
可以做到这一点。我试过了,结果是:Name:Candidates,dtype:int64。我错过了什么吗?Python附带了一个专门的dict,名为“谢谢你,我成功了!”!