[Python] How to create non-alphabetically ordered Categorical column in Polars Dataframe?

Discussão em 'Python' iniciado por Stack, Agosto 8, 2025.

  1. Stack

    Stack Membro Participativo

    In Pandas, you can create an "ordered" Categorical column from existing string column as follows:

    column_values_with_custom_order = ["B", "A", "C"]

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


    In Polars documentation, I couldn't find such way to create ordered columns. However, I could reproduce this by using pl.from_pandas(df) so I suspect that this is possible with Polars as well.

    What would be the recommended way to this?

    I tried to create new column with:

    polars_df.with_columns(col("Column").cast(pl.Categorical))


    but I don't know how to include the custom ordering to this.

    I also checked In polars, can I create a categorical type with levels myself?, but I would prefer not to add another column to my Dataframe only for ordering.

    Continue reading...

Compartilhe esta Página