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

如何在Python Polars数据框中计算字符串长度?

Polars中计算字符串字符数的专属方法

你可以使用Polars字符串命名空间下的str.length()方法,这是专门用于计算字符串长度的原生矢量化方法,比apply结合len的方式效率更高,尤其适合处理大数据集。

示例代码实现:

import polars as pl

df = pl.DataFrame({
    "start_date": ["2020-01-02", "2020-01-03", "2020-01-04", "2020-01-05"],
    "Name": ["John", "Joe", "James", "Jörg"]
})

# 使用Polars原生方法计算字符串长度
result = df.with_columns(pl.col("Name").str.length().alias("Name_length"))
print(result)

运行结果:

shape: (4, 3)
┌────────────┬──────┬─────────────┐
│ start_date ┆ Name ┆ Name_length │
│ ---        ┆ ---  ┆ ---         │
│ str        ┆ str  ┆ i64         │
╞════════════╪══════╪═════════════╡
│ 2020-01-02 ┆ John ┆ 4           │
│ 2020-01-03 ┆ Joe  ┆ 3           │
│ 2020-01-04 ┆ James┆ 5           │
│ 2020-01-05 ┆ Jörg ┆ 4           │
└────────────┴──────┴─────────────┘

补充说明:

  • Polars的字符串方法命名和Pandas略有区别:Pandas用.str.len(),而Polars对应的是.str.length()
  • 该矢量化方法依托Polars内部优化实现,避免了Python层面的循环开销,性能远优于apply方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 00:57:23