Metrokett
Metrokett

Reputation: 29

How do I sum up all numbers in a line in csv file in Python?

Basically I have a .csv file:

math,4,5,5,4,4,5
biology,3,4,4,2,3,2
chemistry,3,5,4,3,4,2
english,5,5,5,4,5,5

And in the end I need it to print the arithmetic mean of the subject:

math: 4.5
biology: 3.0
chemistry: 3.5
english: 4.8 

I've tried some stuff and I got all of the numbers into a one list, but it doesn't help me much.

Edit: Added, what I have so far.

fail = open("grades.csv", encoding = "UTF-8")

info = []
a = []

for row in fail:
    parts = row.strip("\n").split(",")
    info.append(parts)

fail.close()

print(info)

for el in info:
    print(str(el[0]) + ":")
    for i in el[1:]:
        a.append(i)

print(a)

Upvotes: 1

Views: 598

Answers (3)

Suraj
Suraj

Reputation: 2477

dic = {}
for i in range(len(df)):
    subject = df.loc[i].tolist()[0]
    total = df.loc[i].tolist()[1:]
    dic[subject] = sum(total)/len(total)

You can use the tolist() method to separate the subject name and the marks. Then you can calculate the average.

Upvotes: 0

user2390182
user2390182

Reputation: 73490

You should use the csv module to process csv data:

import csv

with open("grades.csv", encoding = "UTF-8") as f:
    for row in csv.reader(f):
        sub, *grades = row
        grades = list(map(float, grades))
        avg = sum(grades) / len(grades)
        print("{}: {}".format(sub, avg))

Upvotes: 2

Tom Ron
Tom Ron

Reputation: 6181

for line in open('myfile.csv'):
    data = line.split(",")
    subject = data[0]
    grades = [float(x) for x in data[1:]]
    print(subject, sum(grades)/len(grades))

Upvotes: 3

Related Questions