我在 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
我是一名优秀的程序员,十分优秀!