简体   繁体   English

如何在 python 中聚合每周数据

[英]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.

相关问题 Pandas:如何每周汇总数据? - Pandas: how to aggregate data weekly? 如何获取有关 Python MetaTrader 5 的每周数据 - How to get weekly data on Python MetaTrader 5 “将数据聚合到每周级别,以便每个产品周组合有一行”是什么意思,我如何使用 python (pandas) 来做到这一点 - what does "Aggregate the data to weekly level, so that there is one row per product-week combination" mean and how can I do it using python (pandas) 如何将用户的日常活动聚合为每周 - how to aggregate daily activities of users into weekly 如何使用 Python 将特定列的每周数据转换为每日数据 - How to transform weekly data to daily for specific columns using Python python - 如何在带有分类和数值列的python中将每日数据转换为每周或每月? - How to convert daily data into weekly or monthly in python with categorical and numerical column? 如何使用 Python 在 Panda 数据框中聚合数据? - How to aggregate data in Panda data frame with Python? 使用Python将每周数据转换为每日数据 - Convert weekly data into daily data with Python 将月度数据转换为周度数据 - Python - Convert monthly data to weekly data - Python Python 将时间戳字符串数据重采样为每周数据 - Python Resample timestamp String Data to weekly data
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM