我有一个如下所示的列表:
list=[
('2013-01-04', u'crid2557171372', 1),
('2013-01-04', u'crid9904536154', 719677),
('2013-01-04', u'crid7990924609', 577352),
('2013-01-04', u'crid7990924609', 399058),
('2013-01-04', u'crid9904536154', 385260),
('2013-01-04', u'crid2557171372', 78873)
]
问题是具有重复ID的第二个col,但计数不同。我需要有一个列表来汇总计数,所以列表看起来像这样。在python中是否有一个cluase小组?
list=[
('2013-01-04', u'crid9904536154', 1104937),
('2013-01-04', u'crid7990924609', 976410),
('2013-01-04', u'crid2557171372', 78874)
]
答案 0 :(得分:6)
让我们为您的列表a
命名,而不是list
(list
是Python中非常有用的功能,我们不想掩盖它):
import itertools as it
a = [('2013-01-04', u'crid2557171372', 1),
('2013-01-04', u'crid9904536154', 719677),
('2013-01-04', u'crid7990924609', 577352),
('2013-01-04', u'crid7990924609', 399058),
('2013-01-04', u'crid9904536154', 385260),
('2013-01-04', u'crid2557171372', 78873)]
b = []
for k,v in it.groupby(sorted(a, key=lambda x: x[:2]), key=lambda x: x[:2]):
b.append(k + (sum(x[2] for x in v),))
b
现在是:
[('2013-01-04', u'crid2557171372', 78874),
('2013-01-04', u'crid7990924609', 976410),
('2013-01-04', u'crid9904536154', 1104937)]
答案 1 :(得分:1)
我认为没有任何内置工具能够完全满足您的需求。但是,使用defaultdict
模块中的collections
滚动自己很容易:
from collections import defaultdict
counts = defaultdict(int)
for date, crid, count in lst:
counts[(date, crid)] += count
new_lst = [(date, crid, count) for (date, crid), count in counts.items()]
这只需要线性运行时间,因此如果您的数据集很大,则可能优于groupby
实施,这需要O(log n)
运行时排序。
答案 2 :(得分:0)
“漫长”的方式:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> r = defaultdict(list)
>>> for i in l:
... d[i[1]] += i[2]
... r[i[0]].append(d)
...
>>> results = []
>>> for i,v in r.iteritems():
... for k in v[0]:
... results.append((i,k,v[0][k]))
...
>>> results
[('2013-01-04', u'crid9904536154', 1104937),
('2013-01-04', u'crid2557171372', 78874),
('2013-01-04', u'crid7990924609', 976410)]
答案 3 :(得分:0)
一种极简主义的方式:
from pandas import *
a = [('2013-01-04', u'crid2557171372', 1),
('2013-01-04', u'crid9904536154', 719677),
('2013-01-04', u'crid7990924609', 577352),
('2013-01-04', u'crid7990924609', 399058),
('2013-01-04', u'crid9904536154', 385260),
('2013-01-04', u'crid2557171372', 78873)]
DataFrame(a).groupby([0,1]).sum().reset_index()
<强>出:强>
0 1 2
0 2013-01-04 crid2557171372 78874
1 2013-01-04 crid7990924609 976410
2 2013-01-04 crid9904536154 1104937