1

We have to compute the average of of the 5th row in an excel sheet, saved as a csv file. The first row of the file has the names of the columns making them strings. I can't seem to get a code that loops around all the row[4] and compute it into one variable 'sum'. Here is my code. Also,

import csv
import os
sum = x_length = 0
with open('2.5_week.csv', newline='') as f:
    rows = csv.reader(f)
    for row in rows:
        if row[4] is int:
            sum = sum + float(row[4])
            x_length = x_length + 1
x_average = sum/len(x_length)
print(x_average)

I'm using python 3.4.x

2 Answers 2

2

This example should help get you towards the goal you are trying to solve with your program:

import csv
import random
import statistics


def main():
    make_csv()
    read_csv_1()
    read_csv_2()


def make_csv():
    with open('2.5_week.csv', 'w', newline='') as file:
        writer = csv.writer(file)
        for index in range(1000):
            row = (random.random() * index,
                   random.randint(index, index * 2),
                   random.randrange(1 + index * 3),
                   random.random() + index,
                   random.randint(index, index + 10),
                   random.randrange(1 + index ** 2))
            writer.writerow(row)


def read_csv_1():
    with open('2.5_week.csv', 'r', newline='') as file:
        table = pivot_table(csv.reader(file))
    print(statistics.mean(map(float, table[4])))


def pivot_table(table):
    iterator = iter(table)
    pivot = tuple([cell] for cell in next(iterator))
    for row in iterator:
        for column, cell in zip(pivot, row):
            column.append(cell)
    return pivot


def read_csv_2():
    with open('2.5_week.csv', 'r', newline='') as file:
        print(statistics.mean(float(row[4]) for row in csv.reader(file)))

if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

Comments

0
total = 0
count = 0

with open("data.csv") as source:
    rdr = csv.reader(source, delimiter=',')
    next(rdr, None) #skip the header
    for row in rdr:
        try:
            if isinstance(float(row[4]),float):
                total+= float(row[4])
                count += 1
        except ValueError:
            pass

ave = round(total / count,2)
print(ave)

4 Comments

It keeps saying 'mag' which is the name of the column, can not be converted from string to float
@JessyWhite if can skip the header with next(rows, None), just after you start the reader, I will update now.
@JessyWhite I have update once again to make more robust
@LetzerWille How do you find out who voted which way? I did not vote but have sometimes wondered who has contributed to the score of a question or answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.