如何将Polars表达式序列化为JSON/YAML文件用于MLOps?
将Polars特征工程配置序列化到JSON并反向解析
我非常认可Polars表达式语法,大量特征工程工作都基于Polars表达式实现。出于MLOps相关需求,我希望将特征工程逻辑迁移至JSON或YAML文件中。请问如何将以下Polars表达式配置编码为JSON文件,且能反向转换为Polars表达式?
configuration = { 'features': [ pl.col('col1').fill_null(0).log().le(0.2).alias('feature1'), pl.col('col2').fill_null(0).log().le(0.2).alias('feature2'), pl.col('col3').fill_null(0).log().le(0.2).alias('feature3') ], 'filters': [ pl.col('col4') >= 500_000, pl.col('col5').is_in(['A', 'B']) ] } # 使用示例(仅作参考) X = (df .filter(pl.all(configuration['filters'])) .select(configuration['features']) )注:此问题与《Possible to Stringize a Polars Expression?》高度相关,但并非重复问题。
核心解决方案
Polars原生支持表达式的JSON序列化与反序列化,通过pl.Expr.to_json()和pl.Expr.from_json()方法可直接完成转换,只需将配置中的每个表达式单独处理后组合成JSON结构即可。
1. 序列化Polars配置到JSON文件
遍历配置中的features和filters列表,将每个表达式转换为JSON字符串,再构建可持久化的JSON结构:
import polars as pl import json # 原始Polars表达式配置 configuration = { 'features': [ pl.col('col1').fill_null(0).log().le(0.2).alias('feature1'), pl.col('col2').fill_null(0).log().le(0.2).alias('feature2'), pl.col('col3').fill_null(0).log().le(0.2).alias('feature3') ], 'filters': [ pl.col('col4') >= 500_000, pl.col('col5').is_in(['A', 'B']) ] } # 序列化每个表达式为JSON字符串 serialized_config = { 'features': [expr.to_json() for expr in configuration['features']], 'filters': [expr.to_json() for expr in configuration['filters']] } # 保存到JSON文件 with open('feature_config.json', 'w') as f: json.dump(serialized_config, f, indent=2)
2. 从JSON反序列化回Polars表达式
读取JSON文件后,用pl.Expr.from_json()解析每个字符串,还原原始表达式配置:
import polars as pl import json # 从JSON文件加载序列化后的配置 with open('feature_config.json', 'r') as f: loaded_serialized = json.load(f) # 反序列化表达式,还原原始配置 deserialized_config = { 'features': [pl.Expr.from_json(expr_str) for expr_str in loaded_serialized['features']], 'filters': [pl.Expr.from_json(expr_str) for expr_str in loaded_serialized['filters']] } # 验证使用逻辑(与原始代码完全一致) # X = (df # .filter(pl.all(deserialized_config['filters'])) # .select(deserialized_config['features']) # )
3. 关键注意事项
- 版本兼容性:确保使用Polars 0.17.0及以上版本,该版本后表达式的JSON序列化功能已稳定支持。
- 复杂表达式处理:常见的链式调用、比较运算、聚合函数等都能正常序列化;若涉及自定义函数,需先注册自定义函数再执行反序列化。
- YAML替代方案:若偏好YAML格式,只需将上述代码中的
json模块替换为yaml模块,逻辑完全一致。
内容的提问来源于stack exchange,提问作者MYK
相关产品推荐
相关产品推荐

