Skip to content Skip to sidebar Skip to footer

Calculate Average And Total From File

Python beginner. How do I present data from a file and calculate total/average for each person? How do I add the value to a variable outside of for in every iteration, and once t

Solution 1:

To calculate the total you can simply do (assuming that you don't want to include the first index, which contains "PersonA", etc.):

line_total = sum(map(int, line2[1:]))

From there, the average is also simple:

line_average = line_total / len(line2[1:])

Explanation:

  • The sum function takes in an iterable (for our purposes think of an iterable as a list) and adds all of its contents using the appropriate sum function.

  • The [1:] is called list splicing. Using this syntax you're telling Python you want to create a new list with the contents of the original list starting at the 1 position. Here's a couple of examples:

    >>>a = [1, 2, 3]>>>b = [1:]>>>b
    [2, 3]
    

The specific syntax is as follows: [start_index : end_index] either the start_index or the end_index can be left blank and Python will fill them in with the start or end of the list respectively.

Solution 2:

This how I would do. That said, there are many ways to get this done in Pyhton.

import pandas as pd

df = pd.read_csv('result.txt', sep=';',header=None)
del df[4]
df['AVERAGE'] = df[[1,2,3]].mean(axis = 1)
df['TOTAL'] = df[[1,2,3]].sum(axis = 1)

I use pandas library for this type of operations.

Output:

0123AVERAGETOTAL0PersonA342454559451.66666713551PersonB444100545363.00000010892PersonC332567491463.33333313903PersonD142612666473.3333331420

Solution 3:

This will work for any values per person, and for any number of persons:

from collections import defaultdict

defmyprint(lines):
    sum_dict = defaultdict(lambda: ([], 0, 0))

    for line in lines:
        data = line.strip().split(";")
        person = data[0].strip()
        values = [int(i) for i in data[1:] if i]
        sum_dict[person] = (values + sum_dict[person][0], sum(values)+sum_dict[person][1], len(values)+sum_dict[person][2])

    for person insorted(sum_dict):
        values, total, nb = sum_dict[person]
        print"{}\t{}\t{}\t{}".format(person, '\t'.join([str(i) for i in values]), total, total/nb)

if __name__ == '__main__':

    import os
    if os.path.exists('result.txt'):
        withopen('result.txt') asinput:
            lines = input.readlines()
    else:
        s = """PersonA;342;454;559;
               PersonB;444;100;545;
               PersonC;332;567;491;
               PersonD;142;612;666;"""
        lines = s.split('\n')

    myprint(lines)

Post a Comment for "Calculate Average And Total From File"