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)レコードを反復処理し、ディクショナリ(ディクショナリキーとしてカスタムタイプのオブジェクト)の複合キー(Name、Produce)を使用して合計を累積します

于 2012-06-12T21:50:50.933 に答える