how to get the sum of a CSV column list to print

sum up values of a field in a csv file python
how to get the average of a csv column in python
how to sum a column in python
pandas sum columns csv
count number of rows in csv python pandas
count rows in csv python
python read csv line by line
how to get the average of a column in python

I need to get the sum of the second column in a csv. I have tried several possible solution but at most, I am only getting Totals = set{} where I would expect to get the sum of the list I created from the second column of the csv file. My csv file looks like this:

I am sure it has to be a simple solution I am missing, but I can't figure it out and have spent hours trying different options I've found, here and on other sites. I would really appreciate any help to point me in the right direction. Also, for this, I can't use modules like Pandas. Here is my code.

    import os
    import csv

    budget_csv = os.path.join("../PyBank", "budget_data.csv")

    with open(budget_csv, newline="") as csvfile:
        csvreader = csv.reader(csvfile, delimiter=",")
        #skip header row
        next(csvreader, None) 

        # Gets number of rows in csv
        data=list(csvreader)

        row_count = len(data)

        totals = []
        for row in csvreader:
            values = row[1]
            totals.append(values)

        print (totals) #did this just to see if it would print the list of values



    print ("Financial Analysis")
    print ("-------------------------------")
    print ("Total Months: ", row_count)
    print ("Total: ", sum(totals))
    print ("Average Change: ")
    print ("Greatest Increase in Profits: ")
    print ("Greatest Decrease in Profits: ")



    output_file = os.path.join("Analysis.txt")

    #  Open the output file
    with open(output_file, "w") as text_file:
        text_file.write (f"Financial Analysis\n")
        text_file.write (f"-------------------------------\n")
        text_file.write (f"Total Months: " + str(row_count) + "\n")
        #print (f"Total: {}".format(net))
        #print (f"Average Change: ")
        #print (f"Greatest Increase in Profits: ")
        #print (f"Greatest Decrease in Profits: ")  

you need to iterate on data, not on csvreader once csvreader is cast as list.

for row in data:

how to get the sum of a CSV column list to print, I have tried several possible solution but at most, I am only getting Totals = set{} where I would expect to get the sum of the list I created from the second column of  If all you want is the sum of one column, then you can add it up yourself: import csv total = 0 with open ('filename.csv', newline='') as csvfile: spamreader = csv.reader (csvfile, delimiter=' ',quotechar='|') for row in spamreader: total += float (row [column#]) Files only work in text as well, so you have to convert to something summable.

Figured it out, finally. Created two new variables. Renamed totals = [] to totals1 = []. Then turned the ints in totals 1 into floats using totals2 = [float(integral) for integral in totals1], which was used to get the sum with totals3 = sum(totals2). New code:

     totals1 = [] for row in data:
         values = row[1] 
         totals1.append(values)          
     totals2 = [float(integral) for integral in totals1] #turns values in totals1 into floats
     totals3 = sum(totals2) 

Summing Columns in CSV File : learnpython, I have tried using print (sum(row[column#])) but haven't had any luck with that or any a list of rows columns = zip(*rows) # transpose the rows into columns total​  Read CSV Columns into list and print on the screen. Read and Print specific columns from the CSV using csv.reader method. Read CSV via csv.DictReader method and Print specific columns. For the below examples, I am using the country.csv file, having the following data:

when you do data=list(csvreader) you consumed csvreader, so it's at the end of the file and when you try to iterate over it again on this line for row in csvreader: it's empty and total remains empty list. I would also recommend using csv.DictReader.

Not tested, bur something like

import os
import csv

budget_csv = os.path.join("../PyBank", "budget_data.csv")

with open(budget_csv, 'r') as csvfile:
    csvreader = csv.DictReader(csvfile, delimiter=",")
    totals = []
    for row_count, row in enumerate(csvreader, start=1):
        value = int(row['Profit/Losses'])
        totals.append(value)


print ("Financial Analysis")
print ("-------------------------------")
print ("Total Months: {}".format(row_count))
print ("Total: {}".format(sum(totals)))
print ("Average Change: ")
print ("Greatest Increase in Profits: ")
print ("Greatest Decrease in Profits: ")



output_file = os.path.join("Analysis.txt")

#  Open the output file
with open(output_file, "w") as text_file:
    text_file.write ("Financial Analysis\n")
    text_file.write ("-------------------------------\n")
    text_file.write ("Total Months: {}\n".format(row_count))

Sum all lines of a csv file, You don't need any temporary values. Just execute awk and redirect output to file​. file_out="output.txt" file_in="input.txt" awk -F, ' { sum = 0; for (i=1; i<=NF; i++)  line_sum = sum(map(float,stripped_line)) (You can use literal_eval to directly do sum (literal_eval (stripped_line)), But the string functions are the right (and preffered way)) Hence the complete code will be reduced to (excluding the data creation part)

Use Pandas to Calculate Stats from an Imported CSV file, To demonstrate how to calculate stats from an imported CSV file, I'll review a Next, you'll need to import the CSV file into Python using this template: Sum of salaries, grouped by the Country column; Count of salaries,  print(df.columns) 2. Access Column Names Using the keys() Method. Second, we can get the exact same result by using the keys() method. That is, we will get the column names by the following code as well. print(df.keys()) 3. Get Column Names by Iterating of the Columns. In the third method, we will simply iterate over the columns to get the

CSV data manipulation, Show how to add a column, headed 'SUM', of the sums of the rows. Ada has no build-in or predefined functions to read or write CSV tables. to read a row (​function Line), to step from column to column (function Next), and to get the items in the column (function Item): (setf data-list ; add list of sums as additional column In this lesson, you will learn how to access rows, columns, cells, and subsets of rows and columns from a pandas dataframe. Let’s open the CSV file again, but this time we will work smarter. We will not download the CSV from the web manually. We will let Python directly access the CSV download URL. Reading a CSV file from a URL with pandas

Python csv column value, Show how to add a column, headed 'SUM', of the sums of the rows. Find where a value exists in a column I am new to python and I have a csv file of the following type id, header1, header2 1, Example 1: Print DataFrame Column Names. C:\Users\Ron\Desktop\stats.csv. So in my case, I applied the following code to import the stats CSV file: import pandas as pd df = pd.read_csv (r'C:\Users\Ron\Desktop\stats.csv') print (df) Step 3: Use Pandas to Calculate Stats from an Imported CSV File. For the final step, the goal is to calculate the following statistics using the pandas package:

Comments
  • Thank you, this kind of worked for me. I was able to get it to print the list of values in the column, but I still can't get the sum to print. I don't get an error message, it just prints Total: 0 . I converted the integers to floats with totals2 = [float(integral) for integral in totals1] but still can't get it to out put the sum. I get invalid syntax when I try print sum(totals2).
  • Thanks @buran but I still couldn't get it to output. I didn't get an error, but for some reason when I try to get the sum value of the list, it just doesn't seem to do anything. This did help get everything in a list though.
  • @TheHoff, my code has been tested based on sample data from your picture and it works as expected. I don't know what you did wrong, but the code works.
  • It did not output the data for me, but then again, I'm sure it would have. I don't remember the exact point I abandoned this and went with the fix I commented above. Thanks for the help though, hopefully it helps someone in the future.