gpt4 book ai didi

python - 如何对 Pandas 中的时间序列数据进行下采样?

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:42 25 4
gpt4 key购买 nike

我在 pandas 中有一个时间序列,看起来像这样(按 id 排序):

id    time    value
1 0 2
1 1 4
1 2 5
1 3 10
1 4 15
1 5 16
1 6 18
1 7 20
2 15 3
2 16 5
2 17 8
2 18 10
4 6 5
4 7 6

我希望每个组 ID 的下采样时间从 1 分钟到 3 分钟不等。并且值是组的最大值(id和3分钟)。

输出应该是这样的:

id    time    value
1 0 5
1 1 16
1 2 20
2 0 8
2 1 10
4 0 6

我试过循环它需要很长时间。

知道如何为大型数据框解决这个问题吗?

谢谢!

最佳答案

您可以将您的time 序列转换为实际的timedelta,然后使用resample 进行矢量化解决方案:

t = pd.to_timedelta(df.time, unit='T')
s = df.set_index(t).groupby('id').resample('3T').last().reset_index(drop=True)
s.assign(time=s.groupby('id').cumcount())

   id  time  value
0 1 0 5
1 1 1 16
2 1 2 20
3 2 0 8
4 2 1 10
5 4 0 6

关于python - 如何对 Pandas 中的时间序列数据进行下采样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52885878/

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