简体   繁体   中英

How to aggregate weekly data in python

I have list of data of the entire year in the following format:

01 5170
01 3490
02 3630
02 3170

First we have the week number(01, 02) and then the corresponding money spent (5170 and 3490 for week1 etc,)

How would i go about adding the money spent so that i get all of the money spent in week1, week2 etc. All money spent in week one should be added together and so on.

So data from above would become:

01  8660
02  6800

Any ideas?

Given:

text = """01 5170
01 3490
02 3630
02 3170"""

xss = [[int(x) for x in s.split(" ")] for s in text.splitlines()]

>>> xss
[[1, 5170], [1, 3490], [2, 3630], [2, 3170]]

We can sort, group, and then reduce (sum):

from itertools import groupby

groups = groupby(xss, key=lambda x: x[0])
result = [(k, sum(x for _, x in xs)) for k, xs in groups]

>>> result
[(1, 8660), (2, 6800)]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM