Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the position of a single column in Python Polars library?

I am working with the Python Polars library for data manipulation on a DataFrame, and I am trying to change the position of a single column. I would like to move a specific column to a different index while keeping the other columns in their respective positions.

One way of doing that is using select, but that requires giving a complete order for all the columns which I don't want to do.

import polars as pl

# Create a simple DataFrame
data = {
    'A': [1, 2, 3],
    'B': [4, 5, 6],
    'C': [7, 8, 9],
    'D': [10, 11, 12]
}

df = pl.DataFrame(data)

I want to move column 'C' to index 1, so the desired output should be:

shape: (3, 4)
┌─────┬─────┬─────┬──────┐
│ A   │ C   │ B   │ D    │
│ --- │ --- │ --- │ ---- │
│ i64 │ i64 │ i64 │ i64  │
╞═════╪═════╪═════╪══════╡
│ 1   │ 7   │ 4   │ 10   │
├─────┼─────┼─────┼──────┤
│ 2   │ 8   │ 5   │ 11   │
├─────┼─────┼─────┼──────┤
│ 3   │ 9   │ 6   │ 12   │
└─────┴─────┴─────┴──────┘
like image 826
Maturin Avatar asked Oct 11 '25 12:10

Maturin


1 Answers

Some attempts:

df.drop("C").insert_column(1, df.get_column("C"))
df.select(df.columns[0], "C", pl.exclude(df.columns[0], "C"))
cols = df.columns
cols[1], cols[2] = cols[2], cols[1]
# cols[1:3] = cols[2:0:-1]

df.select(cols)
shape: (3, 4)
┌─────┬─────┬─────┬─────┐
│ A   ┆ C   ┆ B   ┆ D   │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╪═════╡
│ 1   ┆ 7   ┆ 4   ┆ 10  │
│ 2   ┆ 8   ┆ 5   ┆ 11  │
│ 3   ┆ 9   ┆ 6   ┆ 12  │
└─────┴─────┴─────┴─────┘
like image 72
jqurious Avatar answered Oct 14 '25 10:10

jqurious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!