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

Polars Rust中如何创建存储另一列字符串长度的新列?

Rust Polars 计算字符串长度列实现方案

问题描述

在Rust中复刻Polars Python官方示例,尝试新增列存储指定列的字符串长度时,照搬Python端str.lengths()写法会触发编译错误。
Python端可正常运行的参考代码:

import polars as pl

df = pl.DataFrame({"shakespeare": "All that glitters is not gold".split(" ")})
df = df.with_column(pl.col("shakespeare").str.lengths().alias("letter_count")) 

照搬逻辑编写的Rust报错代码:

use polars::prelude::*;

fn print_length_strings_in_column() -> () {
    let df = generate_df().expect("error");
    let new_df = df
        .lazy()
        .with_column(col("vendor_id").str().lengths().alias("vendor_id_length"))
        .collect();
}

编译抛出错误信息:

no method named lengths found for struct StringNameSpace in the current scope
对应使用的依赖配置(Cargo.toml):

[dependencies]
polars = {version = "0.22.8", features = ["strings", "lazy"]}

查阅文档可知Rust版Polars未实现同名lengths()方法,Utf8命名空间下提供了str_lengths函数,但无明确调用示例。

正确实现方式

Rust端Polars的字符串命名空间(对应Python的str访问器)中,计算字符串长度的方法名为str_lengths(),和Python端命名存在差异,直接替换方法名即可,无需新增依赖。
修正后的可运行代码:

use polars::prelude::*;

fn print_length_strings_in_column() -> PolarsResult<()> {
    let df = generate_df()?;
    let new_df = df
        .lazy()
        // 将原lengths()替换为str_lengths()即可
        .with_column(col("vendor_id").str().str_lengths().alias("vendor_id_length"))
        .collect()?;
    
    println!("{}", new_df);
    Ok(())
}

调用注意事项

  • 已开启strings feature的前提下,不需要额外引入其他trait或模块,可直接调用str_lengths()方法。
  • 该方法返回UInt32类型列,存储每个字符串的字符长度,计算逻辑和Python端str.lengths()完全一致。
  • 惰性查询最终调用collect()会返回PolarsResult<DataFrame>,需要做对应错误处理,不要直接丢弃返回结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 12:24:21