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

如何通过Polars表达式API获取单元格中列表的元素数量?

获取Polars单元格中列表的长度

你可以使用Polars表达式的list.len()方法来计算单元格内列表的长度,这正是你需要的行内列表长度统计方法。

代码示例

import polars as pl

# 创建示例DataFrame
df = pl.DataFrame({
    "fruits": [["apple", "banana"], ["orange"], [], ["grape", "mango", "peach"]]
})

# 添加统计列表长度的列
df = df.with_columns(
    pl.col("fruits").list.len().alias("n_fruits")
)

print(df)

运行后输出:

shape: (4, 2)
┌──────────────────────────┬──────────┐
│ fruits                   ┆ n_fruits │
│ ---                      ┆ ---      │
│ list[str]                ┆ u32      │
╞══════════════════════════╪══════════╡
│ ["apple", "banana"]      ┆ 2        │
│ ["orange"]               ┆ 1        │
│ []                       ┆ 0        │
│ ["grape", "mango", "peach"] ┆ 3    │
└──────────────────────────┴──────────┘

为什么.len()和.count()不行?

  • .len()是列级方法,返回的是整个DataFrame或列的行数,不是单元格内列表的长度。
  • .count()同样是列级统计,返回的是非空值的行数,和列表元素数量无关。

而list.len()是Polars专门为列表类型列提供的方法,会逐行计算每个单元格内列表的元素个数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 15:22:01