将 Polars 表达式序列化为 JSON 或 YAML 文件?

MYK*_*MYK 2 python-polars

我对极坐标表达式语法非常满意,以至于我的很多特征工程都是用极坐标表达式来表达的。

但是,我现在尝试将功能工程转移到 JSON 或 YAML 文件(出于 MLOps 原因)。

问题是 - 我如何将其编码为 JSON 文件:


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'])
      ]
}

# This is how I use it - just for context
X = (df
         .filter(pl.all(configuration['filters']))
         .select(configuration['features'])
       )

Run Code Online (Sandbox Code Playgroud)

关于如何将其序列化(或重写)为 JSON 以便将其转换回 Polars 表达式的任何想法?

请注意,这个问题与Maybe to Stringize a Polars Expression?有很多重叠。,但它不是重复的。

rit*_*e46 8

截至目前,polars >= 0.18.1我们直接支持 json 之间的序列化/反序列化表达式。

def test_expression_json() -> None:
    # create an expression
    e = pl.col("foo").sum().over("bar")
    
    # serialize to json
    json = e.meta.write_json()

    # deserialize back to an expression
    round_tripped = pl.Expr.from_json(json)

    # assert expression equality
    assert round_tripped.meta == e
Run Code Online (Sandbox Code Playgroud)