Search code examples
pythonpython-polars

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   │
└─────┴─────┴─────┴──────┘

Solution

  • Some attempts:

    df.drop("C").insert_at_idx(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  │
    └─────┴─────┴─────┴─────┘