[英]Python: How can I sum integers in a CSV file, while only summing the integers of a certain variable?
我正在嘗試使用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)
所以我已經確保結果/點是實際的整數,並且我過濾掉了第三行(年份),但是我不知道如何從這里繼續。 在此先多謝!
只需將@Mikk的評論放入實際答案中即可。 除import
外的兩行
import pandas as pd
df = pd.read_csv('euro20042016.csv', sep = ';')
print df.groupby('Country')['Points'].sum()
您唯一需要做的額外事情就是更改文件的第一行,以第一行分隔;
而不是,
。
我稍微更改了您的代碼以使用字典,並使用國家/地區名稱作為鍵。 結果字典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)
我決定花點時間處理您的代碼,這就是我想到的。 在這里, 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}
我相信這是您的目標。
如果您在理解任何內容時遇到問題,請在評論中讓我知道。
我有解決方案。 但請確保您的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
我希望這能幫到您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.