如何在读取 python 中的 csv 文件时添加行

how to add rows in while reading csv file in python

这是我的 csv 文件:

我想在元组中添加相同的日期值。

我想要这样的答案:

{
    {'26-03-2020', marks:2923,couse1:2297}, 
    {'27-03-2020', marks:2212,course1:1783}
}

是否有任何简单的解决方案 this.or 我可以只使用一个循环来完成吗?提前致谢。

尝试如下操作

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)

你可以做到这一点 pandas 很容易

import pandas as pd
# read in the csv
# group by the date column, and sum the other columns
# reset index to get the dates as a series
# convert dataframe to dictionary
out = pd.read_csv('file.csv').groupby('date').sum().reset_index().to_dict('records')

#Out I
[{'date': '26-03-2020', 'marks': 2796, 'course1': 2157},
 {'date': '27-03-2020', 'marks': 2212, 'course1': 1783}]

# Out II
# if you insist on having it as a dict of dicts
out = {k['date']: {'marks': k['marks'], 'course1': k['course1']} for k in out }

{
    '26-03-2020': {'marks': 2796, 'course1': 2157},
     '27-03-2020': {'marks': 2212, 'course1': 1783}
}

进一步解释清楚

无法按照您要求的方式获得字典。我上面的例子表明日期是新字典的关键。在您的示例中,您使用的是 , 而不是 :,这是不可能的。