不好意思,爬文还没看到有用groupby这个function累加的例子。
我的资料是 a list of lists. 每个list里有zipcode, date及revenue.例如
大安区在今年1月1日的销售是100元 [106,20140101,100].我想做两件事,一是先
把销售在每个zipcode的每个月加总起来。这部分已经做完了(step 2)。另一个是把月加总
累加起来。这部分(step 3) 就不知道该如何做了。程式改了半天还是从第一笔资料
累加到最后一笔。但我需要的是在各个zipcode内的累加。
为了方便看资料我把它换行排成by column. Python3 有一个accumulate()好像不错用,
但我的版本是2.7.9。可能step 3小小改动就可以得到 desired output.
#step1: some mock data
mock=[[106,201501,100],
[106,201501,200],
[106,201502,300],
[106,201502,400],
[220,201502,200],
[220,201502,300],
[220,201503,400],
[220,201503,500]]
#desired output:
[[106,201501,300],
[106,201502,1000],
[220,201502,500],
[220,201502,1400]]
#step2: sum up revenue for each zipcode and month using groupby()
testlist=[]
for key, group in groupby(mock, lambda x: str(x[0])+ str(x[1])[0:6]):
summation = sum ([ x[2] for x in group]) # monthly sum
testlist.append([key, summation])
print testlist
#step 3: accumulate monthly summed revenue over month for each zipcode
test2=list(zip(*testlist)[1])
print "test2:"
print test2
for key, group in groupby(mock, lambda x: str(x[0])):
for index, value in enumerate(test2):
temp=test2[:index+1]
testlist[index].append(reduce(lambda a,b: a+b, temp))
print "another test2:"
print testlist