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

如何基于字符串列的JSON筛选含area键且type为elec的Polars DataFrame行?

Polars DataFrame 基于JSON列的过滤实现

需求说明

需要过滤Polars DataFrame,仅保留tags列同时满足以下两个条件的行:

  1. JSON字符串中包含area键
  2. JSON字符串中type键的值为"elec"

实现方案(原生表达式API)

方法一:直接在过滤逻辑中解析JSON

import polars as pl

df = pl.DataFrame({
    "tags": ['{"ref":"@1", "area": "livingroom", "type": "elec"}', '{"ref":"@2", "area": "kitchen"}', '{"ref":"@3", "type": "elec"}'],
     "name": ["a", "b", "c"],
})

filtered_df = df.filter(
    # 检查area键存在(不存在则解析后为null)
    pl.col("tags").str.json_parse().struct.field("area").is_not_null() &
    # 检查type值为"elec"
    (pl.col("tags").str.json_parse().struct.field("type") == "elec")
)

print(filtered_df)

方法二:先解析JSON再过滤(更高效)

对于数据量较大的场景,先一次性解析JSON列再过滤,避免重复解析带来的性能损耗:

filtered_df = df.with_columns(
    # 新增解析后的结构体列
    parsed_tags=pl.col("tags").str.json_parse()
).filter(
    pl.col("parsed_tags").struct.field("area").is_not_null() &
    (pl.col("parsed_tags").struct.field("type") == "elec")
).drop("parsed_tags")  # 可选:移除中间生成的解析列

print(filtered_df)

输出结果

两种方法最终都会得到如下过滤后的DataFrame:

┌────────────────────────────────────────────────────┬──────┐
│ tags                                               ┆ name │
│ ---                                                ┆ ---  │
│ str                                                ┆ str  │
╞════════════════════════════════════════════════════╪══════╡
│ {"ref":"@1", "area": "livingroom", "type": "elec"} ┆ a    │
└────────────────────────────────────────────────────┴──────┘

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:40:22