【问题标题】:Editing value from a .csv using Python使用 Python 从 .csv 编辑值
【发布时间】: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()

Produces this:

【问题讨论】:

  • 您是否考虑过为此使用熊猫?
  • 您当前的代码没有语法错误。它的出现在别处。
  • 什么是file?请发布一个完整的示例。

标签: python list csv


【解决方案1】:

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

它将所有parties 添加到各自的列表中如果他们拥有> 0 seats,否则累积other 的总票数。

'Other'在所有rows被解析并得到累计总数后添加:

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 

【讨论】:

  • 非常感谢,我做了一些更改以使您的工作与文件相关,但这是完美的,它正是我想要的!
【解决方案2】:

这是您的 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])

【讨论】:

    【解决方案3】:

    我只是将条件内联。请注意,'is' 仅适用于 int

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

    【讨论】:

      猜你喜欢
      • 2018-04-22
      • 2021-09-28
      • 1970-01-01
      • 2013-10-09
      • 2013-08-16
      • 1970-01-01
      • 1970-01-01
      • 2012-12-24
      • 1970-01-01
      相关资源
      最近更新 更多