1

我有一个看起来像这样的列表:

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)
]

问题是具有 dup id 但计数不同的第二个 col。我需要一个可以汇总计数的列表,因此列表看起来像这样。python中是否有group by cluase?

list=[
     ('2013-01-04', u'crid9904536154', 1104937),
     ('2013-01-04', u'crid7990924609', 976410),
     ('2013-01-04', u'crid2557171372', 78874)
    ]
4

4 回答 4

6

让我们命名您的列表a而不是listlist在 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)]
于 2013-01-08T09:18:50.930 回答
1

我认为没有任何内置工具可以完全满足您的要求。defaultdict但是,使用模块中的 a 很容易自己推出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)运行时间排序的实现要好。

于 2013-01-08T09:28:43.050 回答
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)]
于 2013-01-08T09:33:01.963 回答
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
于 2013-01-08T11:07:21.013 回答