使用Python从.csv编辑值

时间:2018-01-02 16:00:23

标签: python list csv

我有一个看起来像这样的.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")

我已经尝试为seat = 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()

Produces this:

3 个答案:

答案 0 :(得分:1)

这解析一个字符串(由您提供,例如)。在分隔符被剥离后,' '用作分隔符和空格。

它将所有parties添加到相应的列表,如果他们有> 0 seats,否则累计other票。

在解析完所有'Other'之后添加

row并获得累计总数:

import csv

txt = '''Party    Seats    Votes

Party1   84       1584

Party2   61       851

Party3   12       100

Party4   0        82

Party5   0        29

Party6   0        15'''

Party = []
Seats = []
Votes = []

others = 0
reader = csv.reader(txt.splitlines(),  delimiter = ' ', , skipinitialspace = True)
for row in reader:
    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))

for i in range(len(Party)):
    print(Party[i], "    ", Seats[i], "    ", Votes[i])

输出:

Party      Seats      Votes
Party1      84      1584
Party2      61      851
Party3      12      100
Other       0      126 

答案 1 :(得分:0)

我只是把条件内联。注意'''仅适用于int< 10,否则使用'=='(可能是上面语法错误的来源,尽管你没有包含你的尝试)

for row in file:
    Party.append('other' if row[1] is 0 else row[0])
    Seats.append(row[1])
    Votes.append(row[2])

答案 2 :(得分:0)

这是你的csv(,作为分隔符):

Party1,84,1584
Party2,61,851
Party3,12,100
Party4,0,82
Party5,0,29
Party6,0,15

并且:

import pandas as pd


df = pd.read_csv('a.csv', sep=',', header=None)

Party = []
Seats = []
Votes = []

for value in df.values:
    Party.append('Other' if value[1] == 0 else value[0])
    Seats.append(value[1])
    Votes.append(value[2])