pola-rs/polars · error · TypeError

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

DataFrame.__getitem__ dispatches on the first element of a Sequence key: bool → row/column mask, int → column position, str → column name. A first element of any other type (float, None, tuple, nested list) has no selection semantics and raises TypeError naming the type.

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 df599052da)

Solutions

  1. Coerce whole-number floats to int: [int(i) for i in key].
  2. Use strings to select by name or ints to select by position — do not mix types.
  3. Filter out None entries before indexing: [k for k in key if k is not None].

Example fix

// before
cols = df[np.linspace(0, 3, 3).tolist()]  # floats -> TypeError

// after
cols = df[[int(round(i)) for i in np.linspace(0, 3, 3)]]
Defensive patterns

Strategy: type-guard

Validate before calling

def normalize_column_key(key: Sequence):
    if key and isinstance(key[0], float) and all(k.is_integer() for k in key):
        return [int(k) for k in key]
    if not key or not isinstance(key[0], (bool, int, str)):
        raise TypeError(f"column key elements must be bool/int/str, got {type(key[0]).__name__}")
    return key

out = df[normalize_column_key(key)]

Type guard

def is_selectable_column_sequence(key: Sequence) -> bool:
    return not key or isinstance(key[0], (bool, int, str))

Try / catch

try:
    out = df[key]
except TypeError as e:
    if "cannot select columns using Sequence" in str(e):
        out = df[[int(k) for k in key]]  # if keys are whole numbers
    else:
        raise

Prevention

When it happens

Trigger: df[[1.0, 2.0]]; df[[None, "a"]]; df[[("a",)]]; float indices produced by np.linspace or pandas float Index objects.

Common situations: Computed column indices arriving as floats (e.g. np.arange(4) * 0.5 rounded); None values from JSON configs mixed into column lists; tuples from multi-index code ported from pandas.

Related errors


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