Python Forum
how can I write my function output on CSV file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how can I write my function output on CSV file (/thread-17993.html)

Pages: 1 2


RE: how can I write my function output on CSV file - rxndy - May-02-2019

A way that is much faster is:
import pandas as pd

df = pd.read_csv("grades.csv")
grades = df.iloc[:, 1:]
names = df.iloc[:, 0]
averages = grades.mean(axis=1)

output = pd.DataFrame(names, averages)
output.to_csv("Final_grades.csv", index=False)



RE: how can I write my function output on CSV file - buran - May-02-2019

@rxndy, this is most probably just a school project/homework assignment and I doubt they will be allowed to to use pandas
and please fix your code because you will get NameError on line 6 - now it is fixed


RE: how can I write my function output on CSV file - rxndy - May-02-2019

(May-02-2019, 04:52 PM)buran Wrote: @rxndy, this is most probably just a school project/homework assignment and I doubt they will be allowed to to use pandas
and please fix your code because you will get NameError on line 6


True, My bad. I probably just confused people even more.


RE: how can I write my function output on CSV file - go127a - May-05-2019

I have another question.

can I use function and mixed a number of operation on one csv file?

for the same code:

import csv
from statistics import mean
import itertools
from collections import OrderedDict

def calculate_averages(input_file_name, output_file_name):
    with open ('grades.csv', 'r') as input_file_name:
        reader=csv.reader(input_file_name)
        data = []
        for row in reader:
            l2 = []
            name = row[0]
            grades=[int(num) for num in row[1:]] 
            l2.append(name)
            l2.append(float(mean(grades)))
            data.append(l2)
            
    with open('grades.csv', 'w', newline='') as output_file_name:
        writer = csv.writer(output_file_name)
        writer.writerows(data)
and after that i am going to use another function...