1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Drop column by index in polars

Discussão em 'Python' iniciado por Stack, Setembro 16, 2025.

  1. Stack

    Stack Membro Participativo

    I need to drop the first column in a polars DataFrame.

    I looked here and it suggests:

    result = df.select([col for idx, col in enumerate(df.columns) if idx != 1])


    It looks long and clumsy for such a simple task?

    I also tried:

    df.select(pl.exclude(pl.nth(1)))


    but that errored out

    ---------------------------------------------------------------------------
    TypeError Traceback (most recent call last)
    Cell In[20], line 1
    ----> 1 df.select(pl.exclude(pl.nth(1)))

    File \.venv\Lib\site-packages\polars\functions\lazy.py:1855, in exclude(columns, *more_columns)
    1785 def exclude(
    1786 columns: str | PolarsDataType | Collection[str] | Collection[PolarsDataType],
    1787 *more_columns: str | PolarsDataType,
    1788 ) -> Expr:
    1789 """
    1790 Represent all columns except for the given columns.
    1791
    (...) 1853
    1854 """
    -> 1855 return F.col("*").exclude(columns, *more_columns)

    File \.venv\Lib\site-packages\polars\expr\expr.py:851, in Expr.exclude(self, columns, *more_columns)
    768 def exclude(
    769 self,
    770 columns: str | PolarsDataType | Collection[str] | Collection[PolarsDataType],
    771 *more_columns: str | PolarsDataType,
    772 ) -> Expr:
    773 """
    774 Exclude columns from a multi-column expression.
    775
    (...) 849 └──────┘
    850 """
    --> 851 return self.meta.as_selector().exclude(columns, *more_columns).as_expr()

    File .venv\Lib\site-packages\polars\selectors.py:571, in Selector.exclude(self, columns, *more_columns)
    566 else:
    567 msg = (
    568 "invalid input for `exclude`"
    569 f"\n\nExpected one or more `str` or `DataType`; found {item!r} instead."
    570 )
    --> 571 raise TypeError(msg)
    573 if exclude_cols and exclude_dtypes:
    574 msg = "cannot exclude by both column name and dtype; use a selector instead"

    TypeError: invalid input for `exclude`

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

    Continue reading...

Compartilhe esta Página