Quantcast
Viewing latest article 43
Browse Latest Browse All 51

Answer by Louis Maddox for Polars: How to reorder columns in a specific order?

I wrote a plugin for this (on GitHub here), please try it out:

pip install polars-permute

Polars Permute Plugin

A Polars plugin for easily reordering DataFrame columns.

Supports column permutations like prepending, appending, shifting, andswapping.

Installation

python pip install polars-permute[polars]

On older CPUs run:

python pip install polars-permute[polars-lts-cpu]

Features

  • Supports both string column names and Polars expressions
  • Handles single or multiple columns
  • Maintains relative ordering of moved columns
  • Chain operations together
  • Gracefully handles edge cases (non-existent columns, empty inputs)

Usage

The plugin adds a permute namespace to Polars DataFrames withmethods for column reordering:

import polars as plimport polars_permute# Create a sample DataFrame df = pl.DataFrame({  "a": [1, 2, 3],  "b": [4, 5, 6],"c": [7, 8, 9],"d": [10, 11, 12] })# Move column 'd' to the startdf.permute.prepend("d")# Move multiple columns to the enddf.permute.append(["a", "b"])# Move columns to a specific positiondf.permute.at(["b", "c"], index=0)# Shift columns left/rightdf.permute.shift("a", "b", steps=1, direction="right")# Swap two columnsdf.permute.swap("a", "d")

I tried to keep the naming distinct from the names of existing row-wise operations to minimise confusion.


Viewing latest article 43
Browse Latest Browse All 51

Trending Articles