gpt4 book ai didi

python - 在 pyspark 中聚合 5 分钟窗口

转载 作者:行者123 更新时间:2023-11-30 22:47:59 25 4
gpt4 key购买 nike

我有以下数据框df:

User | Datetime         | amount | length
A | 2016-01-01 12:01 | 10 | 20
A | 2016-01-01 12:03 | 6 | 10
A | 2016-01-01 12:05 | 1 | 3
A | 2016-01-01 12:06 | 3 | 5
B | 2016-01-01 12:01 | 10 | 20
B | 2016-01-01 12:02 | 8 | 20

我想有效地使用 pyspark 聚合 5 分钟的时间窗口并进行一些计算 - 例如计算每 5 分钟时间窗口每次使用的平均数量和长度 - df 将如下所示:

User | Datetime         | amount | length
A | 2016-01-01 12:00 | 8 | 15
B | 2016-01-01 12:00 | 2 | 4
A | 2016-01-01 12:05 | 9 | 20

如何以最有效的方式实现这一目标?在 Pandas 中我使用:

df.groupby(['cs_username', pd.TimeGrouper('5Min')].apply(...)

最佳答案

不幸的是,在 pyspark 中,这看起来不像 pandas 那么酷;-)您可以尝试将日期转换为时间戳并使用模数,例如:

import pyspark.sql.functions as F
seconds = 300
seconds_window = F.from_unixtime(F.unix_timestamp('date') - F.unix_timestamp('date') % seconds)
dataframe.withColumn('5_minutes_window', seconds_window)

然后您可以简单地按新列进行分组并执行请求的聚合。

关于python - 在 pyspark 中聚合 5 分钟窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40341213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com