[英]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,)首先我们有周数(01, 02),然后是相应的花费(第 1 周的 5170 和 3490 等)
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.我将如何 go 关于添加花费的钱,以便我得到在第 1 周、第 2 周等花费的所有钱。在第一周花费的所有钱应该加在一起等等。
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)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.