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

如何在Polars中拆分列并提取列表的第n个(或最后一个)元素

如何在Polars中拆分列并提取列表的第n个(或最后一个)元素

你可以利用Polars对List类型的原生支持,直接在链式操作中完成拆分和元素提取,既高效又简洁。以下针对你的需求给出具体方案:

一、一步到位:拆分后直接提取最后一个元素

不需要先单独生成列表列,我们可以在when/then逻辑里直接拆分字符串并提取最后一个元素,用.list.last()方法专门处理取最后一个元素的场景:

import polars as pl

df = pl.DataFrame({
    'type': ['A', 'O', 'B', 'O'],
    'id':   ['CASH', 'ORB.A123', 'CHECK', 'OTC.BV32']
})

result = df.with_columns(
    sub_id=pl.when(pl.col('type') == 'O')
             .then(pl.col('id').str.split('.').list.last())
             .otherwise(None)
)

print(result)

运行后得到的预期输出:

shape: (4, 3)
┌──────┬──────────┬────────────┐
│ type ┆ id       ┆ sub_id     │
│ ---  ┆ ---      ┆ ---        │
│ str  ┆ str      ┆ str        │
╞══════╪══════════╪════════════╡
│ A    ┆ CASH     ┆ null       │
│ O    ┆ ORB.A123 ┆ A123       │
│ B    ┆ CHECK    ┆ null       │
│ O    ┆ OTC.BV32 ┆ BV32       │
└──────┴──────────┴────────────┘

二、提取列表的第n个元素

如果需要提取指定位置的元素(比如第一个、第二个),可以用.list.get(n)方法,索引从0开始计数;如果用负数索引,会从列表末尾反向计数(比如-2表示倒数第二个元素):

比如提取第一个元素:

result = df.with_columns(
    sub_id=pl.when(pl.col('type') == 'O')
             .then(pl.col('id').str.split('.').list.get(0))
             .otherwise(None)
)

输出会是:

shape: (4, 3)
┌──────┬──────────┬────────────┐
│ type ┆ id       ┆ sub_id     │
│ ---  ┆ ---      ┆ ---        │
│ str  ┆ str      ┆ str        │
╞══════╪══════════╪════════════╡
│ A    ┆ CASH     ┆ null       │
│ O    ┆ ORB.A123 ┆ ORB        │
│ B    ┆ CHECK    ┆ null       │
│ O    ┆ OTC.BV32 ┆ OTC        │
└──────┴──────────┴────────────┘

三、如果已经有列表列,如何提取元素

如果你的DataFrame已经存在像之前生成的sub_id列表列,也可以对该列单独处理提取元素:

# 先生成列表列
df = df.with_columns(
    sub_id=pl.when(pl.col('type') == 'O')
             .then(pl.col('id').str.split('.'))
             .otherwise(None)
)

# 提取最后一个元素
df = df.with_columns(
    sub_id_last=pl.col('sub_id').list.last()
)

这样会新增一个sub_id_last列,存储提取后的元素,原列表列也会保留。

关键说明

  • Polars的List类型提供了丰富的方法,比如.first()、.last()、.get()都是专门用来提取元素的API,可读性和性能都很好;
  • 尽量采用链式操作一步完成拆分+提取,避免生成不必要的中间列,提升处理效率。

备注:内容来源于stack exchange,提问作者Phil-ZXX

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 07:54:29