Using python, I need to average value based on two keys in two columns from a CSV file
Question: I have a csv file with 3 columns

    
    
    TMC, EPOCH, Time
    11C12, 1, 24
    11C12, 1, 34
    11C12, 2, 56
    11C12, 2, 78
    11C13, 1, 56
    11C13, 2, 45
    11C13, 2, 64
    11C13, 3, 32
    11C13, 3, 28
    

Now I want to have average.py file which calculates average of time for each
combination of TMC, EPOCH and write that to a txt or csv file

The desired output is:

    
    
    TMC, EPOCH, Average Time
    11C12, 1, average value 
    11C12, 2, average value
    11C13, 1, average value
    11C13, 2, average value
    11C13, 3, average value
    


Answer: Use a `defaultdict` to group the elements using the forst two columns as the
key and appending the times then average and write to the new csv:

    
    
    import csv
    from collections import defaultdict
    
    with open("in.csv") as f, open("average.csv", "w") as out:
        wr = csv.writer(out)
        d = defaultdict(list)
        head = next(f)
        out.write(head)
        for row in csv.reader(f):
            d[tuple(row[:2])].append(int(row[-1]))
    
        for k, v in d.items():
            out.write("{},{},{}\n".format(k[0], k[1], sum(v, 0.0) / len(v)))
    

Output:

    
    
    TMC,EPOCH,Time
    11C12,1,29.0
    11C12,2,67.0
    11C13,1,56.0
    11C13,2,54.5
    11C13,3,30.0
    

If you want to keep the order the elements are first seen you can use an
`OrderedDict`:

    
    
    import csv
    from collections import OrderedDict
    
    with open("in.csv") as f, open("average.csv", "w") as out:
        wr = csv.writer(out)
        d = OrderedDict()
        head = next(f)
        out.write(head)
        for row in csv.reader(f):
            d.setdefault(tuple(row[:2]), []).append(int(row[-1]))
    
        for k, v in d.items():
            out.write("{},{},{}\n".format(k[0], k[1], sum(v, 0.0) / len(v)))
    

