【问题标题】:How to create ordered Categorical column in Polars Dataframe?如何在 Polars Dataframe 中创建有序的分类列?
【发布时间】:2023-02-09 18:59:13
【问题描述】:

在 Pandas 中,您可以从现有字符串列创建一个“有序”分类列,如下所示:

column_values_with_custom_order = ["B", "A", "C"] df["Column"] = pd.Categorical(df.Column, categories=column_values_with_custom_order, ordered=True)

在 Polars 文档中,我找不到创建有序列的方法。但是,我可以使用 pl.from_pandas(df) 重现这一点,所以我怀疑这也适用于 Polars。

推荐的方法是什么?

我尝试使用 polars_df.with_columns(col("Column").cast(pl.categorical)) 创建新列,但我不知道如何将自定义排序包含在其中。

我还检查了https://stackoverflow.com/questions/70934789/in-polars-can-i-create-a-categorical-type-with-levels-myself,但我不想只为了订购而向我的 Dataframe 添加另一列。

【问题讨论】:

    标签: data-science categorical-data python-polars


    【解决方案1】:

    从文档: 使用:

    polars_df.with_columns(col("Column").cast(pl.categorical).set_ordering("lexical"))
    

    doc

    df = pl.DataFrame(
        {"cats": ["z", "z", "k", "a", "b"], "vals": [3, 1, 2, 2, 3]}
    ).with_columns(
        [
            pl.col("cats").cast(pl.Categorical).cat.set_ordering("lexical"),
        ]
    )
    df.sort(["cats", "vals"])
    

    【讨论】:

      猜你喜欢
      • 2023-01-07
      • 2023-01-17
      • 2022-12-18
      • 2022-08-24
      • 1970-01-01
      • 2021-10-24
      • 2022-10-15
      • 1970-01-01
      • 2018-12-10
      相关资源
      最近更新 更多