2

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

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

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

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

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

4

3 回答 3

3

这是它的代码:

如果您有任何问题(或者如果我犯了任何错误),请务必查看评论并在此处回复

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
于 2012-06-13T01:24:53.357 回答
2

打开 Excel 文件后应该非常简单。如果保存为 .csv 文件,请使用以下文档:http ://docs.python.org/library/csv.html

然后使用此链接遍历记录并获取每个名称和类型的总和:http ://www.linuxjournal.com/content/handling-csv-files-python

于 2012-06-12T21:55:59.510 回答
1

1) 使用http://pypi.python.org/pypi/xlrd读取 Excel 文件

2)遍历记录,并使用字典中的复合键(名称,生产)(自定义类型的对象作为字典键)来累加总和

于 2012-06-12T21:50:50.933 回答