pola-rs/polars · error

groups are index not slices

Error message

groups are index not slices

What it means

The mirror of unwrap_idx: unwrap_slice() returns the GroupsSlice (offset/length pairs) and panics with 'groups are index not slices' when groups are stored as GroupsType::Idx (first/all index vectors, the representation used for unsorted/hashed grouping).

Source

Thrown at crates/polars-core/src/frame/group_by/position.rs:513

    /// # Panic
    ///
    /// panics if the groups are a slice.
    pub fn unwrap_idx(&self) -> &GroupsIdx {
        match self {
            GroupsType::Idx(groups) => groups,
            GroupsType::Slice { .. } => panic!("groups are slices not index"),
        }
    }

    /// Get a reference to the `GroupsSlice`.
    ///
    /// # Panic
    ///
    /// panics if the groups are an idx.
    pub fn unwrap_slice(&self) -> &GroupsSlice {
        match self {
            GroupsType::Slice { groups, .. } => groups,
            GroupsType::Idx(_) => panic!("groups are index not slices"),
        }
    }

    pub fn get(&self, index: usize) -> GroupsIndicator<'_> {
        match self {
            GroupsType::Idx(groups) => {
                let first = groups.first[index];
                let all = &groups.all[index];
                GroupsIndicator::Idx((first, all))
            },
            GroupsType::Slice { groups, .. } => GroupsIndicator::Slice(groups[index]),
        }
    }

    /// Get a mutable reference to the `GroupsIdx`.
    ///
    /// # Panic
    ///

View on GitHub (pinned to 68506541d2)

Solutions

  1. Match on GroupsType and handle both variants
  2. Check groups.slice() (Option accessor) before calling unwrap_slice
  3. Force the needed representation with the provided conversion helpers before use

Example fix

// before
let slices = groups.unwrap_slice();

// after
match groups.slice() {
    Some(s) => { /* slice path */ },
    None => { /* GroupsType::Idx path */ },
}
Defensive patterns

Strategy: type-guard

Validate before calling

let is_slice = matches!(groups, GroupsType::Slice { .. });
if !is_slice { /* take idx path or convert */ }

Type guard

fn has_slice_groups(g: &GroupsType) -> bool {
    matches!(g, GroupsType::Slice { .. })
}

Prevention

When it happens

Trigger: Calling GroupsType::unwrap_slice() on groups from a hashed group_by over unsorted keys, or any code path that assumes the sliced representation but receives index-based groups.

Common situations: Code paths tuned for the fast slice representation that receive groups from a generic group_by; polars-internal or plugin code that hard-codes one representation after a schema/plan change alters which grouping strategy runs.

Related errors


AI-assisted analysis of pola-rs/polars@68506541d2 (2026-08-19). Data as JSON: /api/errors/4d329820976443cd. Report an issue: GitHub.