DaveRast
DaveRast

Reputation: 11

Sum of different CSV columns in python

I am quite new to Python and therefore this might seem easy but I am really stuck here.

I have a CSV file with values in a [525599 x 74] matrix. For each column of the 74 columns I would like to have the total sum of all 525599 values saved in one list.

I could not figure out the right way to iterate over each column and save the sum of each column in a list.

Upvotes: 0

Views: 119

Answers (2)

Fred
Fred

Reputation: 1492

Since you're new to python I won't use any fancy libraries like pandas or numpy. But you should definitely check those out some time

import csv

reader = csv.reader(open('your_csv.csv', 'r'))
sums = [0] * 74
for row in reader:
    for i, element in enumerate(row):
        sums[i] += int(element)
print(sums)

Upvotes: 0

Michel Keijzers
Michel Keijzers

Reputation: 15357

Why don't you :

  • create a columnTotal integer array (one index for each column).
  • read the file line by line, per line:
    • Split the line using the comma as separator
    • Convert the splitted string parts to integers
    • Add the value of each column to the columnTotal array's colum index.

Upvotes: 1

Related Questions