Can someone help me do group by function first column, second column and sum third column.
from itertools import groupby
from operator import itemgetter
things = [('2009-09-02','j', 12),
('2009-09-02','j', 3),
('2009-09-03','k',10),
('2009-09-03','k',4),
('2009-09-03','u', 22),
('2009-09-06','m',33)]
for k, items in groupby(things, itemgetter(1)):
for subitem in items:
print(subitem)
got this result:
('2009-09-02', 'j', 12) ('2009-09-02', 'j', 3) ('2009-09-03', 'k', 10) ('2009-09-03', 'k', 4) ('2009-09-03', 'u', 22) ('2009-09-06', 'm', 33)
expecting this result:
('2009-09-02', 'j', 15) ('2009-09-03', 'k', 14) ('2009-09-03', 'u', 22) ('2009-09-06', 'm', 33)
========================================================================
sales = [('Scotland', 'Edinburgh', 20000),
('Scotland', 'Glasgow', 12500),
('Wales', 'Cardiff', 29700),
('Wales', 'Bangor', 12800),
('England', 'London', 90000),
('England', 'Manchester', 45600),
('England', 'London', 29700)]
>>> for a, b in groupby(things, itemgetter(0, 1)):
... print(a, sum(lst[2] for lst in b))
('2009-09-02', 'j') 15
('2009-09-03', 'k') 14
('2009-09-03', 'u') 22
('2009-09-06', 'm') 33
You don't need groupby
as a more efficient way you can use dictionary with dict.setdefault
method :
>>> d={}
>>>
>>> for date,char,val, in things:
... d.setdefault((date,char),[]).append(val)
...
>>> [(i,j,sum(k)) for (i,j),k in d.items()]
[('2009-09-02', 'j', 15), ('2009-09-03', 'u', 22), ('2009-09-06', 'm', 33), ('2009-09-03', 'k', 14)]
>>>
And if you want to use groupby
as a hint you might note that you need to pass the indices to itemgetter
function :
itemgetter(0, 1)
If you want to sum
, you have to sum , simply printing it wouldn't magically sum the values for you.
Also, according to your example, seems like you should groupby based on first and second column. Example -
for k,items in groupby(things, itemgetter(0, 1)):
print(k + (sum(x[2] for x in items),)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.