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

Polars 0.28升级至0.31时upsample方法报错求助

Polars 0.31升级后Upsample报错:分组列未显式标记为已排序

问题场景

升级Polars从0.28到0.31后,执行upsample代码时触发panic:

原代码:

df = df.upsample(&["sensor_id"],
                    "ts", 
                    polars::time::Duration::parse(period),
                    polars::time::Duration::parse("0m")).unwrap();

报错信息:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: InvalidOperation(ErrString("argument in operation 'upsample' is not explicitly sorted

- If your data is ALREADY sorted, set the sorted flag with: '.set_sorted()'.
- If your data is NOT sorted, sort the 'expr/series/column' first.
    "))', /home/glenn/bmos/libbmos/src/lib.rs:4638:58
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

尝试用set_sorted_flag修改写法时触发类型错误:

df = df.upsample(&[col("sensor_id").set_sorted_flag(polars::series::IsSorted::Ascending)],
                    "ts", 
                    polars::time::Duration::parse(period),
                    polars::time::Duration::parse("0m")).unwrap();

错误信息:

the trait bound `polars::prelude::Expr: AsRef<str>` is not satisfied
the following other types implement trait `polars::prelude::IntoVec<T>`:
  <Vec<T> as polars::prelude::IntoVec<T>>
  <bool as polars::prelude::IntoVec<bool>>
required for `&polars::prelude::Expr` to implement `AsRef<str>`
required for `&[polars::prelude::Expr; 1]` to implement `polars::prelude::IntoVec<std::string::String>`

解决方案

Polars 0.31对upsample的要求更严格:必须确保分组列(这里是sensor_id)已排序,且显式标记排序状态。不能直接将带排序标记的Expr传入upsample的分组参数(该参数仅接受列名字符串切片),需按以下两种情况处理:

情况1:数据已按sensor_id和ts排序

如果你的数据已经提前按sensor_id(升序)+ts(升序)排好序,只需先给sensor_id列设置排序标记,再执行upsample:

// 给sensor_id列设置升序排序标记
let df = df.with_column(
    col("sensor_id").set_sorted_flag(polars::series::IsSorted::Ascending)
).unwrap();

// 执行upsample
let df = df.upsample(
    &["sensor_id"],
    "ts",
    polars::time::Duration::parse(period),
    polars::time::Duration::parse("0m")
).unwrap();

情况2:数据未排序

如果数据未排序,必须先按分组列+时间列排序(排序后列会自动带上排序标记),再执行upsample:

// 先按sensor_id和ts升序排序
let df = df.sort(&["sensor_id", "ts"], Default::default()).unwrap();

// 执行upsample
let df = df.upsample(
    &["sensor_id"],
    "ts",
    polars::time::Duration::parse(period),
    polars::time::Duration::parse("0m")
).unwrap();

关键说明

  • Upsample的分组参数by仅接受列名字符串切片,不能直接传入Expr对象,这是你之前触发类型错误的原因。
  • Polars 0.31要求upsample操作的分组列必须显式标记为已排序,目的是保证upsample结果的正确性,避免未排序数据导致的逻辑错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:57:12