如何更简洁地根据多列键值对检索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
相关产品推荐
相关产品推荐

