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

Polars查询优化:Categorical列上的字符串操作疑问

Polars中Categorical列的字符串操作逻辑

Polars处理Categorical列的字符串操作时,优先在体积更小的Categorical字典层面执行,而非先将整列转换为String类型,核心是利用Categorical存储唯一值字典的特性提升效率,具体分两种场景说明:

过滤类字符串操作(如str.contains、str.starts_with)

不需要手动将Categorical列转为String类型,直接调用str.*方法即可。Polars会自动在字典的唯一值上执行字符串匹配检查,再将结果映射回原列,性能远高于转String后操作。

  • 冗余写法(不推荐):
    df.filter(pl.col('my_category').cast(pl.String).str.contains("target"))
    
  • 最优写法:
    df.filter(pl.col('my_category').str.contains("target"))
    

修改类字符串操作(如str.replace)

这类操作会生成新的字符串值,Polars依然会先在字典的唯一值上执行替换逻辑,再基于新的唯一值生成新的Categorical字典,无需手动来回转换类型。

  • 冗余写法(不推荐):
    df.with_columns(pl.col('my_category').cast(pl.String).str.replace("old", "new").cast(pl.Categorical))
    
  • 最优写法:
    df.with_columns(pl.col('my_category').str.replace("old", "new").cast(pl.Categorical))
    

补充说明

如果修改类操作生成了大量新的唯一值,Categorical的空间优势会有所下降,但Polars仍会保持字典层面的处理逻辑,整体效率依然优于直接使用String列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 12:52:01