move_cols_to_start

move_cols_to_start(columns, *more_columns)

Returns a list of Polars expressions that reorder columns so the specified columns appear first.

You may specify either column names or data types, but not a combination of both.

Parameters

columns : str | PolarsDataType | Collection[str] | Collection[PolarsDataType]

The name or datatype of the column(s) to move. Accepts regular expression input. Regular expressions should start with ^ and end with $.

*more_columns : str | PolarsDataType = ()

Additional names or datatypes of columns to move, specified as positional arguments.

Returns

: list[pl.Expr]

A list of expressions to reorder columns.

Examples

DataFrame Context

The list of expressions returned by move_cols_to_start() take effect only within the select() context. Using them in with_columns() will have no effect, and the result will remain unchanged.

import polars as pl
import turtle_island as ti

df = pl.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"], "c": [4.4, 5.5, 6.6]})
df
shape: (3, 3)
abc
i64strf64
1"x"4.4
2"y"5.5
3"z"6.6

Reorder columns so that selected columns appear first:

df.select(ti.move_cols_to_start("c", "b"))
shape: (3, 3)
cba
f64stri64
4.4"x"1
5.5"y"2
6.6"z"3

Reorder by data type:

df.select(ti.move_cols_to_start([pl.Float64, pl.String]))
shape: (3, 3)
bca
strf64i64
"x"4.41
"y"5.52
"z"6.63

Note that when selecting by data type, the moved columns will follow the original order in the DataFrame schema.

df.select(ti.move_cols_to_start([pl.String, pl.Float64]))
shape: (3, 3)
bca
strf64i64
"x"4.41
"y"5.52
"z"6.63