代码之家  ›  专栏  ›  技术社区  ›  gggg

根据物理值创建分类系列

  •  2
  • gggg  · 技术社区  · 11 月前

    我想创建一个分类列,其中每个类别都有一个用于自我文档的描述性名称。我有一个与分类列中的物理值等效的整数列表,我想在不创建要传递的中间字符串列表的情况下创建分类列 pl.Series .

    import polars as pl
    
    dt = pl.Enum(["0", "1", "2"])
    s1 = pl.Series(["0", "0", "2", "1"], dtype=dt)
    physical = list(s1.to_physical())
    print(f"{physical=}")
    s2 = pl.Series([str(p) for p in physical], dtype=dt)
    assert s1.equals(s2)
    
    # turning physical to strings just to create the series which is stored as ints is a waste of compute power
    # how to construct a series from the physical values?
    s2 = pl.Series.from_physical(physical, dtype=dt)
    assert s1.equals(s3)
    

    这张照片

    physical=[0, 0, 2, 1]
    

    然后它出错了,因为 Series.to_physical 不存在。是否有类似的功能 from_physical 这会使这个代码段运行到完成,而不会在最后的断言中出错吗?

    2 回复  |  直到 11 月前
        1
  •  2
  •   Hericks    11 月前

    你可以简单地 cast 转换为枚举数据类型。

    assert s1.equals(s1.to_physical().cast(dt)) # True
    
        2
  •  2
  •   Cameron Riddell    11 月前

    你可以 polars.Expr.cast 将物理整数数组转换为 polars.datatypes.Enum 以如下方式表示枚举的类别:

    import polars as pl
    
    enum = pl.Enum([*'abcd'])
    df = pl.DataFrame({
        'physical': [0, 0, 1, 2, 0, 3],
    })
    
    print(
        df.with_columns(
            categories=pl.col('physical').cast(enum)
        )
    )
    # shape: (6, 2)
    # ┌──────────┬────────────┐
    # │ physical ┆ categories │
    # │ ---      ┆ ---        │
    # │ i64      ┆ enum       │
    # ╞══════════╪════════════╡
    # │ 0        ┆ a          │
    # │ 0        ┆ a          │
    # │ 1        ┆ b          │
    # │ 2        ┆ c          │
    # │ 0        ┆ a          │
    # │ 3        ┆ d          │
    # └──────────┴────────────┘