【发布时间】:2018-01-02 16:00:23
【问题描述】:
我有一个看起来像这样的 .csv 文件:
Party Seats Votes
Party1 84 1584
Party2 61 851
Party3 12 100
Party4 0 82
Party5 0 29
Party6 0 15
我已将每个单独的列收集到一个列表中,我想将所有没有获得席位的政党归为“其他”政党,并将他们的投票合并为一个图表。
Party = []
Seats = []
Votes = []
for row in file:
Party.append(row[0])
Seats.append(row[1])
Votes.append(row[2])
#create "other" party for 0 seat candidates
Party.append("Other")
我已经尝试对座位 = 0 使用“if”循环,但我认为这是错误的方法,因为它不起作用并返回:
SyntaxError: invalid syntax
提前致谢。
如果有人需要,以下是已完成/工作的代码。
import numpy as np
import matplotlib.pylplot as plt
import csv
outfile = open("UK_votes2017.csv","r")
file=csv.reader(outfile)
#skip the headers (party/seats/votes)
next(file, None)
#just a quick test to make sure i've read the data in.
'''for line in file:
t=line[0], line[1], line[2]
print(t)
'''
Party = []
Seats = []
Votes = []
others = 0
for row in file:
if row: # needed for the empty rows in aboves txt
if row[1].strip() == "0":
others += int(row[2]) # sum up
else:
Party.append(row[0])
Seats.append(row[1])
Votes.append(row[2])
Party.append("Others") # added summed others
Seats.append("0")
Votes.append(str(others))
plt.pie(Votes, labels=Party)
plt.show()
【问题讨论】:
-
您是否考虑过为此使用熊猫?
-
您当前的代码没有语法错误。它的出现在别处。
-
什么是
file?请发布一个完整的示例。