这是我的csv文件:
我想在元组中添加相同的日期值。到目前为止,我已经做到了:
actuals = namedtuple('actuals', 'marks course1')
with open('file.csv') as csv_file:
reader = csv.reader(csv_file, delimiter=',')
for row in reader:
for row1 in reader:
if row['date']== row1['date']:
row1['marks']= row1['marks']+row['marks']
row1['course1']= row1['course1']+row['course1']
report(row1['date'])=actuals(marks,course1)
if row['date']!= row1['date']:
break
return report
我想要这样的答案:{{'26 -03-2020',mark:2923,couse1:2297},{'27 -03-2020',mark:2212,course1:1783}}有什么简单的解决方案吗?或者我可以只使用一个循环就可以做到吗?提前致谢。
import csv, io
data = '''\
date,marks,course1
26-03-2020,1,10
26-03-2020,2,20
26-03-2020,4,40
27-03-2020,100,2
27-03-2020,200,4
27-03-2020,400,8
'''
out = {}
f = io.StringIO(data)
reader = csv.DictReader(f)
for r in reader:
k = r['date']
m = int(r['marks'])
c = int(r['course1'])
if k in out:
out[k]['marks'] += m
out[k]['course1'] += c
else:
out[k] = {'marks': m, 'course1': c}
print(out)