python - 如何获取要打印的 CSV 列列表的总和

标签 python python-3.x csv sum

我需要获取 csv 中第二列的总和。我尝试了几种可能的解决方案,但最多只能得到 Totals = set{} 我希望获得从 csv 文件的第二列创建的列表的总和。我的 csv 文件如下所示:enter image description here

我确信这一定是我所缺少的一个简单的解决方案,但我无法弄清楚,并且花了几个小时尝试我在此处和其他网站上找到的不同选项。我真的很感激任何帮助我指明正确方向的帮助。另外,为此,我不能使用 Pandas 这样的模块。这是我的代码。

    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: ")  

最佳答案

一旦 csvreader 转换为列表,您需要迭代数据,而不是 csvreader。

for row in data:

关于python - 如何获取要打印的 CSV 列列表的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53710235/

相关文章:

python - 不同类型的类命名之间的区别

date - 将 datetime.now().date() 与 Python 中的日期常量进行比较

javascript - 如果行太多,Chrome 无法导出到 csv?

python - psycopg2 - 字段 "id"缺少数据时出错?

python - 如何打印 Gridsearch 中每个组合的准确度分数?

python - 在 Python 中随机化字符串列表的最佳方法

python-3.x - 如何使用Scikit learn CountVectorizer?

python - 使用 Python 读取 CSV 文件的值

python - 如何使用 "pytest_terminal_summary"钩子(Hook)避免额外的换行

python - 为 numpy、scipy 和 matplotlib 的 intersphinx 链接指定目标