我有一个像这样的 Polars 数据框
df = pl.DataFrame(
{
"tags": ['{"ref":"@1", "area": "livingroom", "type": "elec"}', '{"ref":"@2", "area": "kitchen"}', '{"ref":"@3", "type": "elec"}'],
"name": ["a", "b", "c"],
})
┌────────────────────────────────────────────────────┬──────┐
│ tags ┆ name │
│ --- ┆ --- │
│ str ┆ str │
╞════════════════════════════════════════════════════╪══════╡
│ {"ref":"@1", "area": "livingroom", "type": "elec"} ┆ a │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ {"ref":"@2", "area": "kitchen"} ┆ b │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ {"ref":"@3", "type": "elec"} ┆ c │
└────────────────────────────────────────────────────┴──────┘
我要做的是创建一个过滤函数,根据标签列过滤数据帧。
即我只想留下行
其中标签列有一个区域键和一个具有值 elec 的类型键
我怎样才能做到这一点?
最好使用原生表达式 API,但这并不重要。
谢谢
pl.Expr.str.json_decode
获取包含 JSON 信息的 struct 列。接下来,您可以取消嵌套该结构列并根据上述条件过滤数据框。
(
df
.with_columns(
pl.col("tags").str.json_decode()
)
.unnest("tags")
.filter(
pl.col("area").is_not_null(),
pl.col("type") == "elec",
)
)
shape: (1, 4)
┌─────┬────────────┬──────┬──────┐
│ ref ┆ area ┆ type ┆ name │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str │
╞═════╪════════════╪══════╪══════╡
│ @1 ┆ livingroom ┆ elec ┆ a │
└─────┴────────────┴──────┴──────┘