作者luenchang (luen)
看板Python
标题[问题] 用groupby()做累加
时间Wed Mar 25 18:29:45 2015
不好意思,爬文还没看到有用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
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 60.248.164.177
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1427279388.A.B26.html
1F:→ luenchang: mock data少打了日期,应该是20150101共8码。desired 03/25 18:37
2F:→ luenchang: output的yearMonth则是正确的。sorry 03/25 18:38
3F:→ ccwang002: 你 step3 会每次重头都累叫是因为你 group 完还是 03/26 01:20
4F:→ ccwang002: temp=test2[:index+1] 重头再累加一次,没用到 group 03/26 01:21
5F:推 Yukirin: 何不用pandas 03/26 13:10