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

如何使用Polars LazyFrame拼接两列最后一个字符生成新列?

正确用Polars LazyFrame实现两列最后字符拼接的方法

你的代码逻辑有误,(pl.col("col1")[-1] + pl.col('col2'))[-1]会先把col1的最后一个字符和整个col2字符串拼接,再取这个拼接结果的最后一个字符,最终只得到了col2的最后一个字符,完全不符合需求。

正确的做法是分别对两列做strip处理,再提取各自的最后一个字符,最后将这两个字符拼接起来。以下是完整实现:

import polars as pl

# 创建测试DataFrame
df = pl.DataFrame({"col1":["abc","def"], "col2":["ghi","jkl"]})

# 使用LazyFrame实现需求
result = df.lazy().with_columns(
    (pl.col("col1").str.strip().str[-1] + pl.col("col2").str.strip().str[-1]).alias("last_letters_concat")
).collect()

print(result)

输出结果:

shape: (2, 3)
┌──────┬──────┬─────────────────────┐
│ col1 ┆ col2 ┆ last_letters_concat │
│ ---  ┆ ---  ┆ ---                 │
│ str  ┆ str  ┆ str                 │
╞══════╪══════╪═════════════════════╡
│ abc  ┆ ghi  ┆ ci                  │
│ def  ┆ jkl  ┆ fl                  │
└──────┴──────┴─────────────────────┘

关键说明:

  • pl.col("col1").str.strip():对应Pandas里的str.strip(),去除字符串首尾空白
  • .str[-1]:提取字符串的最后一个字符,也可以用.str.slice(-1)实现相同效果
  • 两个处理后的字符直接用+拼接,最后通过alias()指定新列名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 12:10:33