You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polars高效实现:为每行查找符合差值条件的下一个未来值及时间

高效实现Polars DataFrame的下一个满足条件的未来值匹配

给定示例DataFrame:

import polars as pl

testDF = pl.DataFrame({
    "datetime": [0, 1, 2, 3, 4, 5],
    "values":   [3, 2, 5, 4, 8, 4]
})

需求为添加两列:future_value(每行对应值的下一个满足abs(future_value - original_value) >= 2的未来值)和future_value_datetime(对应未来值的datetime),最终结果需与示例输出一致。

高效实现方案

避免使用iterrows这类循环操作,改用Polars原生的矢量化连接与聚合操作,代码如下:

result = (
    # 为原表添加行索引,用于后续分组匹配
    testDF
    .with_row_index("idx")
    # 自连接,仅保留当前行之后的未来数据
    .join(
        testDF.with_row_index("future_idx"),
        how="left",
        condition=pl.col("datetime") < pl.col("datetime_right")
    )
    # 过滤满足差值条件的行
    .filter(pl.abs(pl.col("values_right") - pl.col("values")) >= 2)
    # 按原行索引排序,确保取到最早的未来值
    .sort(["idx", "datetime_right"])
    # 按原行分组,提取第一个满足条件的未来值和对应datetime
    .group_by("idx")
    .agg(
        future_value=pl.col("values_right").first(),
        future_value_datetime=pl.col("datetime_right").first()
    )
    # 与原表连接,补全未找到匹配的行(填充None)
    .join(testDF.with_row_index("idx"), on="idx", how="right")
    # 清理临时列并按datetime排序
    .drop("idx")
    .sort("datetime")
)

print(result)

方案优势

该方案全程使用Polars的矢量化操作,避免了Python层面的循环计算,在数据量较大时性能远优于iterrows。通过自连接筛选未来数据、分组取首个匹配项的逻辑,精准满足需求且符合Polars的高效计算范式。

输出结果与预期一致:

shape: (6, 4)
┌──────────┬────────┬──────────────┬──────────────────────┐
│ datetime ┆ values ┆ future_value ┆ future_value_datetime │
│ ---      ┆ ---    ┆ ---          ┆ ---                  │
│ i64      ┆ i64    ┆ i64          ┆ i64                  │
╞══════════╪════════╪══════════════╪══════════════════════╡
│ 0        ┆ 3      ┆ 5            ┆ 2                    │
│ 1        ┆ 2      ┆ 5            ┆ 2                    │
│ 2        ┆ 5      ┆ 8            ┆ 4                    │
│ 3        ┆ 4      ┆ 8            ┆ 4                    │
│ 4        ┆ 8      ┆ 4            ┆ 5                    │
│ 5        ┆ 4      ┆ null         ┆ null                 │
└──────────┴────────┴──────────────┴──────────────────────┘

内容的提问来源于stack exchange,提问作者ml1990

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:22:26