2016-09-30 78 views
4

我是python的新手,我現在可以真正使用你的幫助和指導。我想基於第一和第二列讀三米的cols一個CSV文件,並做一些計算即通過動態創建嵌套字典來計算聚合

A spent 100  A spent 2040 
A earned 60 
B earned 48 
B earned 180 
A spent 40 
. 
. 
. 

其中A花了2040將是除了所有「A」和「花」數額。這不會給我一個錯誤,但它不是邏輯上是正確:

for row in rows: 
    cols = row.split(",") 
    truck = cols[0] 
    if (truck != 'A' and truck != 'B'): 
     continue 
    record = cols[1] 
    if(record != "earned" and record != "spent"): 
     continue 
    amount = int(cols[2]) 
    #print(truck+" "+record+" "+str(amount)) 

    if truck in entries: 
     #entriesA[truck].update(record) 
     if record in records: 
      records[record].append(amount) 
     else: 
      records[record] = [amount] 
    else: 
     entries[truck] = records 
     if record in records: 
      records[record].append(amount) 
     else: 
      entries[truck][record] = [amount] 
print(entries) 

我知道,這部分不正確,因爲我會被添加相同的內部詞典列表外的字典,但我不知道如何從那裏:

entries[truck] = records 
if record in records: 
    records[record].append(amount) 

然而,林不知道的語法來動態創建一個新的字典,不會是「記錄」

我越來越:

{'B': {'earned': [60, 48], 'spent': [100]}, 'A': {'earned': [60, 48], 'spent': [100]}} 

但希望能得到:

{'B': {'earned': [48]}, 'A': {'earned': [60], 'spent': [100]}} 

感謝。

+0

這個術語是*「A的總支出是2040」*。是的,熊貓包是這樣做的,強烈推薦。 – smci

+1

更好地短語問題*「如何計算聚合?」*比詢問實現*「創建嵌套字典」*。閱讀有關拆分應用組合範例。 – smci

+0

在你的預期結果中,你爲什麼期望B的收入是48而不是228?類似的花費,不應該是140嗎?你提到了你的問題的總和,但現在看來你只想要第一個? – chthonicdaemon

回答

0
if record in entries[truck]: 
    entries[truck][record].append(amount) 
else: 
    entries[truck][record] = [amount] 

我相信這是你想要的嗎?現在我們直接訪問卡車的記錄,而不是試圖檢查本地字典records。就像你如果沒有卡車進入一樣。

+0

謝謝@Nysten,但我仍然有同樣的問題 – Heap

2

對於你在這裏做的計算,我強烈推薦Pandas

假設in.csv看起來是這樣的:

truck,type,amount 
A,spent,100 
A,earned,60 
B,earned,48 
B,earned,180 
A,spent,40 

你可以做的共計有三行代碼:

import pandas 
df = pandas.read_csv('in.csv') 
totals = df.groupby(['truck', 'type']).sum() 

totals現在看起來是這樣的:

   amount 
truck type   
A  earned  60 
     spent  140 
B  earned  228 

你會發現熊貓可以讓你在更高的層次上思考,避免煩惱在這種情況下使用較低級別的數據結構。