【问题标题】:Python: How can I sum integers in a CSV file, while only summing the integers of a certain variable?Python:如何对 CSV 文件中的整数求和,而只对某个变量的整数求和?
【发布时间】:2017-01-18 12:49:07
【问题描述】:

我正在尝试使用 Python 在 csvfile 中编写一些数据。我有一份欧洲歌唱大赛国家名单和结果,如下所示:

Country,Points,Year
Belgium;181;2016
Netherlands;153;2016
Australia;511;2016
Belgium;217;2015
Australia;196;2015

等等。

总而言之,我想总结任何国家/地区多年来获得的总积分,因此输出应如下所示: '比利时:398','荷兰:153','澳大利亚:707'等等。

这是我的代码的样子:

import csv
with open('euro20042016.csv', 'r') as csvfile:
    pointsallyears = []
    countriesallyears = []
    readFILE = csv.reader(csvfile, delimiter=';')
    for row in readFILE:
        countriesallyears.append(row[0])
        pointsallyears.append(row[1])
csvfile.close()

results = []
for result in pointsallyears:
    result = int(result)
    results.append(result)

scorebord = zip(countriesallyears,results)

所以我已经确保结果/点是实际整数,并且我过滤掉了第三行(年份),但我不知道如何从这里开始。提前非常感谢!

【问题讨论】:

  • 您是否有任何特殊原因要手动逐行读取文件?这是可以在pandas:pandas.pydata.org 中完成的基本操作(两行:读取 csv 和 groupby)。

标签: python windows list python-3.x csv


【解决方案1】:

只需将@Mikk 的评论放入实际答案中即可。除了import之外的两行

import pandas as pd
df = pd.read_csv('euro20042016.csv', sep = ';')
print df.groupby('Country')['Points'].sum()

您需要做的唯一额外的事情是将文件的第一行更改为由; 而不是, 分隔。

【讨论】:

    【解决方案2】:

    我稍微更改了您的代码以使用字典并使用国家/地区名称作为键。结果字典 d 将国家名称作为键,值是总分。

    import csv
    
    d = dict()
    
    with open('euro20042016.csv', 'r') as csvfile:
        readFILE = csv.reader(csvfile, delimiter=';')
        print (readFILE)
        c_list = []
        for row in readFILE:
            if row[0] in c_list:
                d[row[0]] = d[row[0]] + int(row[1])
            else:
                c_list.append(row[0])
                d[row[0]] = int(row[1])
    csvfile.close()
    
    print(d)
    

    【讨论】:

      【解决方案3】:

      我决定尝试一下您的代码,这就是我想出的。这里,row[0] 包含国家名称,row[1] 包含我们需要的值。我们检查该国家/地区是否已经存在于我们用来维护聚合的字典中,如果不存在,我们就创建它。

      import csv
      with open('euro20042016.csv', 'r') as csvfile:
      score_dict={}
      readFILE = csv.reader(csvfile, delimiter=';')
      for row in readFILE:
          # Only rows with 3 elements have the data we need
          if len(row) == 3:
              if row[0] in score_dict:
                  score_dict[row[0]]+=int(row[1])
              else:
                  score_dict[row[0]]=int(row[1])
      csvfile.close()
      print score_dict
      

      我得到的输出是这样的

      {'Belgium': 398, 'Australia': 707, 'Netherlands': 153}
      

      我相信这就是你的目标。

      如果您在理解任何内容时遇到问题,请在 cmets 中告诉我。

      【讨论】:

        【解决方案4】:

        我有解决办法。但请确保您的 euro20042016.csv 文件与

        Belgium;181;2016
        Netherlands;153;2016
        Australia;511;2016
        Belgium;217;2015
        Australia;196;2015
        

        并且这段代码在列表中得到输出。喜欢

        [('Belgium', 398), ('Australia', 707), ('Netherlands', 153)]
        

        代码在这里

        try:
            f = open('euro20042016.csv', 'r+')
            s = f.read()
        
            lst = list(map(lambda x: x.split(';'), s.split('\n')))
        
            points, country = [], []
            for line in lst:
                points.append(int(line[1]))
                country.append(line[0])
        
            countrypoints = sorted(zip(country, points), key=lambda x: x[1])
            country = list(set(country))
            total = [0]*len(country)
        
            for rec in countrypoints:
                total[country.index(rec[0])] = total[country.index(
                    rec[0])] + rec[1]
            f.close()
            finalTotal = list(zip(country, total))
            print finalTotal
        
        except IOError as ex:
            print ex
        except Exception as ex:
            print ex
        

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-08-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多