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

如何在Rust Polars中解析并过滤字符串列?

问题描述

我有一个包含字符串列的DataFrame,示例如下:

let df = df!("names" => &["None", "0", "1", "15", "1|2", "5 ??", "293 ", "XX"]);

我需要将其过滤为仅包含单个整数(允许多位)且该整数大于0的行,同时需要去除首尾空格(若parse()方法自动处理则无需额外操作)。所有数字不会超过3000,上述示例中符合条件的行索引为2、3、6。

我找到的相关解答不符合需求,Polars用户指南的过滤页面仅展示了简单案例,可能我未找到正确的文档页面?

以下代码可成功移除所有"0",但我不想逐个排除内容:

let filtered = df
    .lazy()
    .filter(col("names").neq(lit("0")))
    .collect()?;
println!("filtered: {}", filtered);

更新1:类型转换遇到的问题

看起来我需要通过字符串类型转换创建新的整数列,可能需要使用CastOptions::NonStrict,但我无法实现……当尝试使用CastOptions枚举时,编译器提示它是私有成员?同时,在col("names")后调用cast_with_options时,出现错误“no method named cast_with_options found for enum Expr in the current scope”,但文档中对普通cast()的调用方式就是如此,我现在非常困惑。以下代码无法运行:

use polars::chunked_array::cast::CastOptions; // Error

// ...

let out = df
    .clone()
    .lazy()
    .select([col("names")
        .cast_with_options(DataType::UInt16, CastOptions::NonStrict) // Error
        .alias("int_names")])
    .collect()?;
println!("post-cast: {}", out);

更新2:完整错误信息

1  error[E0603]: struct `CastOptions` is private
  --> rust/orphaned_splits.rs:5:34
   |
5 | use polars::chunked_array::cast::CastOptions;
   |                                  ^^^^^^^^^^^ private struct
   |
note: the struct `CastOptions` is defined here
  --> /Users/nick/.cargo/registry/src/index.crates.io-6f17d22bba15001f/polars-core-0.38.3/src/chunked_array/cast.rs:3:5
   |
3 | use arrow::compute::cast::CastOptions;
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: import `CastOptions` directly
   |
5 | use polars_arrow::compute::cast::CastOptions;
   |     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

2  error[E0599]: no method named `cast_with_options` found for enum `Expr` in the current scope
    --> rust/orphaned_splits.rs:151:14
     |
150 |           .select([col("names")
     |  __________________-
151 | |             .cast_with_options(DataType::UInt16, CastOptions::NonStrict)
     | |_____________-^^^^^^^^^^^^^^^^^
     |
help: there is a method `over_with_options` with a similar name
   |
151 |             .over_with_options(DataType::UInt16, CastOptions::NonStrict)
     |              ~~~~~~~~~~~~~~~~~

更新3:依赖配置

polars = { version = "0.38.3", features = ["parquet", "lazy", "dtype-categorical", "dtype-i16"] }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 21:20:58