Python Sum Excel文件 [英] Python Sum excel file

查看:82
本文介绍了Python Sum Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含3列的Excel文件.
请在下面举例

I have an excel file that has 3 columns.
Please example below

Name      Produce     Number
Adam      oranges     6
bob       Apples      5
Adam      Apples      4
steve     Peppers     7
bob       Peppers     16
Adam      oranges     5

我需要以这种方式在python中生成总和

I need to generate the sum in python in such a way

Name      Produce     Number
Adam      oranges     11
bob       apples      5
steve     peppers     7
etc

我是python的新手,试图弄清楚如何写每个人的输出合计?有没有一种简单的方法可以从excel收集这些数据?

I am new to python and trying to figure out how to write the output of each persons totals? is there an easy way to gather this data from excel?

推荐答案

以下是代码:

如果您有任何疑问(或我有任何错误),请务必查看评论并在此处发帖

Be sure to look at the comments and post back here if you have any questions (or if I made any mistakes)

import csv

file  = open('names.csv', "rb") #Open CSV File in Read Mode
reader = csv.reader(file)      #Create reader object which iterates over lines

class Object:                   #Object to store unique data
    def __init__(self, name, produce, amount):
        self.name = name
        self.produce = produce
        self.amount = amount

rownum = 0 #Row Number currently iterating over
list = []  #List to store objects

def checkList(name, produce, amount):

    for object in list:  #Iterate through list        
        if object.name == name and object.produce == produce:  #Check if name and produce combination exists
            object.amount += int(amount) #If it does add to amount variable and break out
            return

    newObject = Object(name, produce, int(amount)) #Create a new object with new name, produce, and amount
    list.append(newObject)  #Add to list and break out


for row in reader:  #Iterate through all the rows
    if rownum == 0:  #Store header row seperately to not get confused
        header = row
    else:
        name = row[0]  #Store name
        produce = row[1]  #Store produce
        amount = row[2]  #Store amount

        if len(list) == 0:  #Default case if list = 0
            newObject = Object(name, produce, int(amount))
            list.append(newObject)
        else:  #If not...
            checkList(name, produce, amount)


rownum += 1

for each in list: #Print out result
    print each.name, each.produce, each.amount

file.close() #Close file

这篇关于Python Sum Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆