pola-rs/polars · error

cannot select columns using Sequence with elements of type

Error message

cannot select columns using Sequence with elements of type {qualified_type_name(first)!r}

What it means

_select_columns handles DataFrame column selection via getitem. A Sequence key is accepted only when every element is a str (name) or int (column index). If the first element is any other type, polars cannot tell whether the sequence means names or indices and raises TypeError naming the element type.

Solutions

  1. Use a consistent all-str list for names: df[['a', 'b']].
  2. Or a consistent all-int list for positions: df[[0, 2]].
  3. Use df.select(...) with expressions for mixed/programmatic selection.
  4. Cast numeric entries to str if they are actually names, or to int if positional.
  5. Remove None or non-str placeholders from the column list first.

Example fix

// before
df[['name', 0]]
// after
df[['name', 'age']]  # or df.select(pl.col('name'), pl.col(0) if positional via df[:, [0]])
Defensive patterns

Strategy: validation

Validate before calling

cols = ['a', 'b']
assert all(isinstance(c, str) for c in cols) or all(isinstance(c, int) for c in cols), 'mixed column selector'
df[cols]

Type guard

def is_valid_column_list(key: object) -> bool:
    return (isinstance(key, (list, tuple)) and len(key) > 0 and
            (all(isinstance(x, str) for x in key) or all(isinstance(x, int) for x in key)))

Try / catch

try:
    out = df[cols]
except TypeError as e:
    if 'cannot select columns using Sequence' in str(e):
        out = df.select([str(c) for c in cols])
    else:
        raise

Prevention

When it happens

Trigger: df[['a', 0]] (mixed str/int); df[[None]]; df[[1.0]]; df[[('a',)]] passed to DataFrame getitem for column selection.

Common situations: Mixing column names with positional indices copied from pandas code; list comprehension producing floats; passing a column list containing None placeholders; building selectors programmatically where a numeric id leaked into a name list.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18). Data as JSON: /api/errors/1bdb38e5dc5cff5e. Report an issue: GitHub.

Appendix: source

Thrown at py-polars/src/polars/_utils/getitem.py:220

        rng = range(df.width)[int_slice]
        return _select_columns_by_index(df, rng)

    elif isinstance(key, range):
        return _select_columns_by_index(df, key)

    elif isinstance(key, Sequence):
        if not key:
            return df.__class__()
        first = key[0]
        if isinstance(first, bool):
            return _select_columns_by_mask(df, key)  # type: ignore[arg-type]
        elif isinstance(first, int):
            return _select_columns_by_index(df, key)  # type: ignore[arg-type]
        elif isinstance(first, str):
            return _select_columns_by_name(df, key)  # type: ignore[arg-type]
        else:
            msg = f"cannot select columns using Sequence with elements of type {qualified_type_name(first)!r}"
            raise TypeError(msg)

    elif isinstance(key, pl.Series):
        if key.is_empty():
            return df.__class__()
        dtype = key.dtype
        if dtype == String:
            return _select_columns_by_name(df, key)
        elif dtype.is_integer():
            return _select_columns_by_index(df, key)
        elif dtype == Boolean:
            return _select_columns_by_mask(df, key)
        else:
            msg = f"cannot select columns using Series of type {dtype}"
            raise TypeError(msg)

    elif _check_for_numpy(key) and isinstance(key, np.ndarray):
        if key.ndim == 0:
            key = np.atleast_1d(key)

View on GitHub (pinned to fe841f959e)