我有一只熊猫df,是泥泞或不太像
ID key dist
0 1 57 1
1 2 22 1
2 3 12 1
3 4 45 1
4 5 94 1
5 6 36 1
6 7 38 1
.....
这个测向包含几百万个点。我现在正在尝试生成一些描述符来合并数据的时间特性。我的想法是为每一行创建一个长度为x的窗口,返回数据并计算窗口中特定键的出现次数。我做了一个实现,但是根据我对23个不同窗口的估计,计算将运行32天。这是密码
^{pr2}$有多个不同长度的窗户。然而,我有一种不安的感觉,迭代可能不是这种数据聚合的最聪明的方式。有没有办法实现它以更快的速度运行?在
在一个玩具示例数据帧上,使用
apply()
而不是iterrows()
,可以实现大约7倍的加速。在以下是一些示例数据,从OP扩展到包含多个
key
值:根据这些数据和OP定义的计数标准,我们期望输出为:
^{pr2}$使用OP的方法:
使用
apply()
:请注意,对于数百万条记录,这仍然需要一段时间,并且与这个小测试用例相比,相对的性能提升可能会有所减少。在
更新
这里有一个更快的解决方案,使用
groupby()
和cumsum()
。我制作了一些示例数据,这些数据似乎与所提供的示例大致一致,但包含1000万行。计算平均在一秒钟内完成:现在性能测试:
这里有足够的输出来证明计算是有效的:
注意:要将
ID
从索引还原为列,请在末尾使用df.reset_index()
。在相关问题 更多 >
编程相关推荐