bigd
bigd

Reputation: 69

Creating a list of column averages from a csv file

I know I asked this before, but I'm still not sure why I get this error when I try to test this function. Can anyone please help me fix this?

new_list.append(new_list[i] + num_list[i]) builtins.TypeError: unsupported operand type(s) for +: 'int' and 'str'

Here is the file:

Last Name,First Name,Student No.,uTORid,A1,A2,A3,A4
Smith, Joe,9911991199,smithjoe9,99,88,77,66
Ash, Wood,9912334456,ashwood,11,22,33,44
Full, Kare,9913243567,fullkare,78,58,68,88

I want to get the class average of each assignment. Like the sum of 99, 11, and 78 and then find the average of that. Same with the other assignments.

def class_avg(open_file):
'''(file) -> list of float
Return a list of assignment averages for the entire class given the open
class file. The returned list should contain assignment averages in the 
order listed in the given file.  For example, if there are 3 assignments 
per student, the returned list should 3 floats representing the 3 averages.
class_avg -> [assignment_1_class_avg, assignment_2_class_avg...]
[62.666666666666664, 56.0, 59.333333333333336, 66.0]
'''
new_list = []
count = 0
for line in open_file:
    num_list = line.split(',')[4:]
    for i in range(len(num_list)):
        new_list.append(count)
        new_list.append(new_list[i] + num_list[i])
        count +=1
        avg = sum(float(new_list))/len(new_list)
return new_list

Upvotes: 0

Views: 57

Answers (1)

joaofbsm
joaofbsm

Reputation: 635

As Patrick Artner stated in the comments, you are adding an int and a string together, causing the error. Using the pandas library for CSV reading is really useful for situations like this one:

import pandas as pd

def class_avg(file_path):
    df = pd.read_csv(file_path)

    not_grades = 4  # Number of attributes that are not grades
    total_attributes = len(df.columns)
    avg = []

    for i in range(not_grades, total_attributes):
        avg.append(df.iloc[:, i].mean(axis=0))  # Get the column by index and calculate its mean

    return avg

This code does exactly what you want. You need to state how many attributes come before the grades though, because they are not the only ones with numbers (otherwise it would calculate the mean of the student's number as well).

Upvotes: 1

Related Questions