2014-02-18 51 views
1

這是我的數據的格式:組按日期的列表而進行計數的行值

Date hits returning 
2014/02/06 10 0 
2014/02/06 25 0 
2014/02/07 11 0 
2014/02/07 31 1 
2014/02/07 3 2 
2014/02/08 6 0 
2014/02/08 4 3 
2014/02/08 17 0 
2014/02/08 1 0 
2014/02/09 6 0 
2014/02/09 8 1 

所需輸出是:

date, sum_hits, sum_returning, sum_total 
2014/02/06 35 0 35 
2014/02/07 44 3 47 
2014/02/08 28 3 31 
2014/02/09 14 1 15 

的輸出是用於使用Google Charts

爲了獲得唯一的日期,並計算每行的值,我創建了一本字典,並使用日期有關鍵字,如:

# hits = <object with the input data> 
data = {} 
for h in hits: 
    day = h.day_hour.strftime('%Y/%m/%d') 
    if day in data: 
     t_hits = int(data[day][0] + h.hits) 
     t_returning = int(data[day][1] + h.returning) 
     data[day] = [t_hits, t_returning, t_hits + t_returning] 
    else: 
     data[day] = [ 
      h.hits, 
      h.returning, 
      int(h.hits + h.returning)] 

這將創建類似:

{ 
    '2014/02/06' = [35 0 35], 
    '2014/02/07' = [44 3 47], 
    '2014/02/08' = [28 3 31], 
    '2014/02/09' = [14 1 15] 
} 

和創建所需的輸出我這樣做:

array() 
for k, v in data.items(): 
    row = [k] 
    row.extend(v) 
    array.append(row) 

它創建與所需格式的數組:

[ 
[2014/02/06, 35, 0, 35], 
[2014/02/07, 44, 3, 47], 
[2014/02/08, 28, 3, 31], 
[2014/02/09, 14, 1, 15], 
] 

所以我的問題基本上是,如果有更好的方法做到這一點,或者一些python的內部命令,可以讓我按行字段進行分組,同時對行值進行計數。

+0

是您的輸入按日期排序? –

+0

是,按日期排序 – nbari

+0

然後下面的答案是正確的方法;使用'groupby'。 –

回答

1

如果您的輸入始終排序(或者您可以對其進行排序),則可以使用itertools.groupby來簡化其中的一些操作。顧名思義,groupby通過鍵對輸入元素進行分組,併爲您提供(group_key,list_of_values_in_group)的迭代。類似以下內容應該可以工作:

import itertools 

# the keyfunc extracts the key from each input element 
keyfunc = lambda row: row.day_hour.strftime("%Y/%m/%d") 

data = [] 
for day, day_rows in itertools.groupby(hits, key=keyfunc): 
    sum_hits = 0 
    sum_returning = 0 
    for row in day_rows: 
     sum_hits += int(row.hits) 
     sum_returning += int(row.returning) 
    data.append([day, sum_hits, sum_returning, sum_hits + sum_returning]) 

# data now contains your desired output 
相關問題