Sum Rows from csvreader with common value Python

Viewed 23

I'm reading a csv file in Python,

my file is like:

2,PIPPO,
5,PIPPO,
10,PIPPO,
15,PIPPO,
11,PLUTO,
8,PLUTO,
8,PAPERINO,
6,PAPERINO,

here is my code, I need the sum of column1 grouping by column2, i.e. PIPPO - 32 PLUTO - 19 PAPERINO - 14

name_current=""
name_previous=""
sum=""
with open('input_csv/input_file.csv', newline='') as csvfile:
  numline = len(csvfile.readlines())
  csvfile.seek(0)
  dati = csv.reader(csvfile, delimiter=',', quotechar='|')
  next(dati, None)
  next(dati, None)

  for i, row in enumerate(dati):
    if (name_current == name_previous):
      name_current=row[1]
      row[0]+=row[0]
      sum = ??
   
    name_previous = name_current
    print(name_current + sum)

How can I do that? thanks

1 Answers

You can use following example how to read from CSV file and group/sum the rows:

import csv

out = {}
with open("your_file.csv", "r") as f_in:
    reader = csv.reader(f_in)

    for cnt, name, *rest in reader:
        out[name] = out.get(name, 0) + int(cnt)

print(out)

Prints:

{"PIPPO": 32, "PLUTO": 19, "PAPERINO": 14}
Related