Create a polars expression that maps the "alphabet" values to numbers that respect the desired order of the column values using Expr.replace
. Use the DataFrame.sort
method to sort the rows first by "currency" value in descending order, and second by the previous expression value (in ascending order).
with pl.StringCache():
df = pl.DataFrame({
"currency": ["EUR","EUR","EUR","USD","USD","USD"],
"alphabet": ["A","B","C","A","B","C"]
})
abc_order = {val: idx for idx, val in enumerate(["C", "A", "B"])}
res = df.sort(pl.col("currency"),
pl.col("alphabet").replace_strict(abc_order),
descending=[True, False])
Output:
>>> res
shape: (6, 2)
┌──────────┬──────────┐
│ currency ┆ alphabet │
│ --- ┆ --- │
│ str ┆ str │
╞══════════╪══════════╡
│ USD ┆ C │
│ USD ┆ A │
│ USD ┆ B │
│ EUR ┆ C │
│ EUR ┆ A │
│ EUR ┆ B │
└──────────┴──────────┘