我正在尝试使用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}")
最简单的方法是使用pandas库。
用于pip install pandas
在机器上安装熊猫
接着
import pandas as pd
df = pd.read_csv('your_filename.csv')
sumcol = df['Profit/Losses'].sum()
print(sumcol)
该和现在在sumcol对象中。供将来参考,如果您的任务是使用csv文件中提供的数据,那么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)
或者,如果要使用阅读器而不是字典阅读器,则需要忽略第一行。像这样
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句