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

Python Polars:在单个with_columns中生成两列表成对元素并过滤Null组

解决方案

完全可以在单次with_columns操作中实现需求,以下是具体代码:

import polars as pl

df = pl.DataFrame({
    "Movie": [[None, "IT",]],
    "Count": [[30, 27]],
})

result = df.with_columns(
    data=pl.zip("Movie", "Count")
    .list.eval(pl.struct(Movie=pl.element().0, Count=pl.element().1))
    .list.filter(pl.element().Movie.is_not_null())
    .list.first()
)

print(result)

代码说明:

  • pl.zip("Movie", "Count"):将Movie和Count两个列表按位置配对,生成元组组成的列表
  • .list.eval(pl.struct(...)):把每个元组转换为包含Movie和Count字段的Struct
  • .list.filter(pl.element().Movie.is_not_null()):过滤掉Movie字段为Null的Struct元素
  • .list.first():取过滤后列表中的第一个元素(对应示例中唯一有效的配对)

执行后输出结果与你的期望一致:

shape: (1, 1)
┌───────────────┐
│ data          │
│ ---           │
│ struct[2]     │
╞═══════════════╡
│ {"IT", 27}    │
└───────────────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 20:12:02