Python 对 CSV 进行排序和求和

标签 python csv datetime

我有这样的 CSV 文件:

Datetime, Usage1, Project1
Datetime, Usage2, Project1
Datetime, Usage3, Project2
Datetime, Usage4, Project3

目标是汇总每个项目的使用情况并生成如下报告:

Project1: Usage1 Usage2

Project2: Usage3

Project3: Usage4

我从以下 Python 代码开始,但它无法正常工作:

#/usr/bin/python

# obtain all Project values into new list project_tags:

project_tags = []
ifile = open("file.csv","r")
reader = csv.reader(ifile)
headerline = ifile.next()
for row in reader:
    project_tags.append(str(row[2]))
ifile.close()

# obtain sorted and unique list and put it into a new list project_tags2
project_tags2 = []
for p in list(set(project_tags)):
    project_tags2.append(p)


# open CSV file again and compare it with new unique list
ifile2 = open("file.csv","r")
reader2 = csv.reader(ifile2)
headerline = ifile2.next()

# Loop through both new list and a CSV file, and if they matches sum it:

sum_per_project = sum_per_project + int(row[29])
for project in project_tags2:
    for row in reader2:
        if row[2] == project:
            sum_per_project = sum_per_project + int(row[1])

欢迎任何意见!

提前致谢。

最佳答案

尝试以下代码段:

summary = {}

with open("file.csv", "r") as fp:
    for line in fp:
        row = line.rstrip().split(',')

        key = row[2]
        if key in summary:
            summary[key] += (row[1].strip(),)
        else:
            summary[key] = (row[1].strip(),)

for k in summary:
    print('{0}: {1}'.format(k, ' '.join(summary[k])))

根据您在 csv 文件中的示例数据,它将打印:

 Project1: Usage1 Usage2
 Project2: Usage3
 Project3: Usage4

关于Python 对 CSV 进行排序和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36016540/

相关文章:

python - Zope 3 + windows + MySQL - 如何在 windows 上安装 ZMySQLDA?

python - (scikit-image) HOG 可视化图像在保存时显示为黑色

mysql & INTO OUTFILE - 转义或替换数据中的新行

python - 根据索引日期时间过滤器设置列值

python - 为什么从 CSV 文件导入数据时出现此 DBeaver 错误?

python - 迭代包含字典中的键的列。从第二个字典返回匹配的键,保持第一个字典中键的顺序

windows - Powershell 使用 Foreach-ObjectFast 和 Where-ObjectFast

java - 服务器时间与本地时间不一致如何处理?

javascript - 在javascript中限制正则表达式中的日期和月份

python - 如何使用线程进行客户端服务器应用程序的功能测试?