2025, Oct 01 13:00

Drop the First Column in a Polars DataFrame Using Selectors (sx.by_index) — Clean, Idiomatic Approach

Learn how to drop the first column in a Polars DataFrame using selectors (sx.by_index). Avoid exclude errors and swap clumsy lists for short, readable code.

Dropping the first column in a Polars DataFrame sounds trivial, but the straightforward path isn’t always obvious. If you’ve reached for a manual list of column names or tried to exclude using an expression, you likely saw it get verbose or fail with a type error. Here’s a clean, idiomatic way to do it with selectors.

Problem statement

You want to remove the first column from a Polars DataFrame.

Naive attempt that works but feels clumsy

This approach builds a filtered list of column names and feeds it to select. It works, but it’s not elegant:

outcome = table.select([name for pos, name in enumerate(table.columns) if pos != 0])

Attempt that fails with a type error

Trying to exclude by using an expression results in an error:

sheet.select(pl.exclude(pl.nth(0)))

TypeError: invalid input for `exclude`

Expected one or more `str` or `DataType`; found <Expr ['cs.nth(1, require_all=true)'] at 0x21A964B6350> instead.

Why this happens

The exclude API expects actual column names or DataType values. Passing an expression object isn’t supported there, which is exactly what the error message reports. So the comprehension is verbose, and the expression-based exclude is invalid for this use case.

Solution: selectors and set notation

Polars selectors provide a concise, expressive way to address columns by position and combine them with set operations. To drop the first column, simply negate the selector for the first index during selection:

from polars import selectors as sx

grid.select(~sx.by_index(0))

If you prefer to see it with set notation or exclusion syntax, these variants are also possible:

from polars import selectors as sx

grid.select(sx.all() - sx.by_index(1))

grid.select(sx.exclude(sx.by_index(1)))

Why this is worth knowing

Selectors keep the code short and readable, avoid fragile list gymnastics, and align directly with documented, idiomatic patterns. It’s easier to understand at a glance and less error-prone than building column lists manually. When you see errors about invalid input for exclude, it’s a hint to switch to selectors rather than passing expressions where names or types are expected.

Takeaway

For column removal by position, use selectors. The most succinct way to drop the first column is:

from polars import selectors as sx

grid.select(~sx.by_index(0))

Keep this pattern in your toolkit and skip the clumsy list filtering or incompatible exclude calls.

The article is based on a question from StackOverflow by robertspierre and an answer by Dean MacGregor.