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

如何更简洁地根据多列键值对检索Polars DataFrame的行?

更简便的Polars复合键行检索方法

你可以利用Polars内置的pl.col().is_in()方法,直接传入字典实现多列匹配,比reduce的写法更简洁直观:

row_index = {'treatment': 'red', 'batch': 'C', 'unit': 76}

# 生成匹配表达式
expr = pl.struct(row_index.keys()).is_in([row_index])

# 检索行
row = df.row(by_predicate=expr)

或者更紧凑的写法:

row = df.row(by_predicate=pl.struct(row_index.keys()).is_in([row_index]))

原理说明

  • pl.struct(row_index.keys())会把指定的列打包成一个结构体列
  • is_in([row_index])会检查每行的结构体是否和目标字典匹配,自动完成多列的逻辑与判断

如果需要确保只返回匹配的第一行(或唯一行),也可以结合filter和fetch_one:

row = df.filter(pl.struct(row_index.keys()).is_in([row_index])).fetch_one()

这个方法完全利用Polars内置功能,不需要额外导入reduce或and_,代码更简洁且可读性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:37:03