首页 > 解决方案 > 使用 python 对 .csv 文件中的列求和

问题描述

我正在尝试使用 python 对 csv 文件中的列求和。这是 csv 数据的示例;

Date,Profit/Losses
Jan-2010,867884
Feb-2010,984655
Mar-2010,322013
Apr-2010,-69417
May-2010,310503
Jun-2010,522857
Jul-2010,1033096
Aug-2010,604885
Sep-2010,-216386

我想总结利润/损失列。我正在使用以下代码,但它返回一个 0。我哪里出错了?

import os
import csv

# Path to collect data from the csv file in the Resources folder
pybank_csv = os.path.join("resources", "budget_data.csv")

with open(pybank_csv, 'r') as csvfile:       
   csvreader = csv.reader(csvfile, delimiter=',')
   next(csvfile, None)    
   t = sum(float(row[1]) for row in csvreader)

   #print the results
   print(f"Total: {t}")

标签: pythoncsv

解决方案


最简单的方法是使用 pandas 库。

用于pip install pandas在您的机器上安装 pandas

进而

import pandas as pd
df = pd.read_csv('your_filename.csv')
sumcol = df['Profit/Losses'].sum()
print(sumcol)

总和现在在 sumcol 对象中。为了将来参考,如果您的任务是使用 csv 文件中提供的数据,pandas 是一种祝福。该库为您提供了数千种不同类型的操作,您可以对数据执行这些操作。有关更多信息,请参阅Pandas 网站

如果您只想使用 csv 包,那么您可以将 csv 作为 dict 读取,然后对每一行的 dict 的利润/损失条目求和

total = 0
with open('your_filename.csv', newline='') as csvfile:
    data = csv.DictReader(csvfile)
    for row in data:
        total = total + int(row['Profit/Losses'])
print(total)

或者如果你想使用 reader 而不是 dict reader,你需要忽略第一行。像这样的东西

total = 0
with open('your_filename.csv', newline='') as csvfile:
    data = csv.reader(csvfile)
    for row in data:
        if not str(row[1]).startswith('P'):
            total = total + int(row[1])
 print(total)

推荐阅读