python - 使用 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}")
解决方案
最简单的方法是使用 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)
推荐阅读
- algorithm - 找到具有到 S 的路径的 N 个最高成本顶点,其中 S 是无向图 G 中的一个顶点
- git - Docker镜像丢弃文件,涉及Sonatype Nexus
- r - read_tsv 将数据错误地解析为 R
- angular - 如何在编译另一个函数时调用一个函数?
- docker - Jenkins 无法在具有特定运行参数的声明性管道中启动 docker 代理容器
- java - 通知不起作用 - Android Studio
- python - 添加具有在两个数据帧上应用 UDF 的结果的列
- ssl - 使用 SSL 连接到已编目 Db2 数据库的 SQLDriverConnect 函数的正确连接字符串是什么?
- servicestack - 从连接表中选择 OrmLite 新对象进行插入
- mailchimp - Mailchimp (mandrill) 交易电子邮件:如何将自定义数据添加到电子邮件模板?