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

如何在Python Polars中截取字符串列的前n个字符?

在Polars中截取字符串列前N个字符的正确写法

Polars的str命名空间对象不支持Pandas那样的下标切片语法(str[:2]),这就是你遇到TypeError的原因。正确的写法是使用Polars提供的字符串方法:

方法1:使用str.slice()

通过指定起始位置和截取长度来获取前2个字符:

pl.col('ColumnA').str.slice(0, 2)

方法2:使用str.head()

如果仅需保留前N个字符,str.head()是更简洁的选择,直接传入字符数量即可:

pl.col('ColumnA').str.head(2)

完整示例

import polars as pl

# 创建测试数据
df = pl.DataFrame({'ColumnA': ['abcde', 'fghij', 'klmno']})

# 添加截取后的新列
result = df.with_columns(
    pl.col('ColumnA').str.head(2).alias('FirstTwoChars')
)

print(result)

输出结果:

shape: (3, 2)
┌─────────┬──────────────┐
│ ColumnA ┆ FirstTwoChars│
│ ---     ┆ ---          │
│ str     ┆ str          │
╞═════════╪══════════════╡
│ abcde   ┆ ab           │
│ fghij   ┆ fg           │
│ klmno   ┆ kl           │
└─────────┴──────────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:12:37