Sort by numerical value of a substring at the start of a Categorical column in Polars
14:24 28 Aug 2023

I have the following Polars dataframe

import polars as pl

df = pl.from_repr("""
┌─────────────────────────────────┬─────────┐
│ Steps                           ┆ UserIds │
│ ---                             ┆ ---     │
│ cat                             ┆ i64     │
╞═════════════════════════════════╪═════════╡
│ 2-Informa localizacao e CPF     ┆ 229889  │
│ 1-Onboarding + Escolhe Segmento ┆ 383133  │
│ 6-Define metodo de pagamento    ┆ 37520   │
│ 10-Omg Hello                    ┆ 12345   │
│ 3-Escolhe plano                 ┆ 95487   │
│ 4-Realiza cadastro              ┆ 46027   │
└─────────────────────────────────┴─────────┘
""")

Is there a easy way to sort that categorical data so the string that starts with the value 1- would be the first row, 2- the second and so on.

expected = pl.from_repr("""
┌─────────────────────────────────┬─────────┐
│ Steps                           ┆ UserIds │
│ ---                             ┆ ---     │
│ cat                             ┆ i64     │
╞═════════════════════════════════╪═════════╡
│ 1-Onboarding + Escolhe Segmento ┆ 383133  │
│ 2-Informa localizacao e CPF     ┆ 229889  │
│ 3-Escolhe plano                 ┆ 95487   │
│ 4-Realiza cadastro              ┆ 46027   │
│ 6-Define metodo de pagamento    ┆ 37520   │
│ 10-Omg Hello                    ┆ 12345   │
└─────────────────────────────────┴─────────┘
""")

It is worth noting that the numerical columns are are not always in a perfect descending order.

python dataframe sorting python-polars