pola-rs/polars · error · InvalidOperation
`unique` operation not supported for dtype
Error message
`unique` operation not supported for dtype `{}` What it means
`agg_n_unique` computes the number of distinct values per group, but Object-dtype (and otherwise object-containing) Series have no physical representation on which distinctness can be computed, so the aggregation panics with an 'operation not supported for dtype' message. The unsafe function first strips to the physical representation and detects object presence via `dtype.contains_objects()`.
Solutions
- Exclude object-dtype columns from the n_unique aggregation (filter columns with `dtype.contains_objects()` first).
- Convert the object column to a comparable dtype (e.g. String via a custom formatter/Display) before aggregating.
- Drop the object column before group_by and re-join results afterwards.
Example fix
// before
df.group_by(["k"])?.agg([col("obj_col").n_unique()])?;
// after
let cols: Vec<_> = df.get_column_names()
.into_iter()
.filter(|n| !df.column(n).unwrap().dtype().contains_objects())
.collect();
df.group_by(["k"])?.agg(cols.iter().map(|n| col(*n).n_unique()).collect::<Vec<_>>())?; Defensive patterns
Strategy: type-guard
Validate before calling
if df.column("obj_col")?.dtype().contains_objects() {
// skip n_unique on this column
} Type guard
fn supports_n_unique(s: &Series) -> bool {
!s.dtype().contains_objects()
} Try / catch
// panic-based, not catchable in stable Rust; guard instead:
for name in cols {
if supports_n_unique(df.column(name)?) {
aggs.push(col(name).n_unique());
}
} Prevention
- Keep Object columns out of aggregation expressions.
- Convert object columns to String/physical dtypes before group_by.
- Audit dtypes with `df.schema()` before generic aggregations.
When it happens
Trigger: A group_by followed by `n_unique` (or agg list containing n_unique) on a column whose dtype is Object / contains objects, e.g. a column of arbitrary Rust structs inserted into a DataFrame.
Common situations: Mixing opaque Rust types into DataFrames and then running group aggregations; using n_unique in a custom expression list applied to all columns including object columns.
Related errors
- creating extension types not allowed - try setting the…
- dtype not yet supported in checked div
- groups are index not slices
- groups are slices not index
- multiple nested objects not yet supported
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/4b636fe64717e24d.
Report an issue: GitHub.
Appendix: source
Thrown at crates/polars-core/src/frame/group_by/aggregations/dispatch.rs:289
return None;
}
let v = mask.sliced_unchecked(first as usize, len as usize);
let tz = v.trailing_zeros() as IdxSize;
if tz == len { None } else { Some(len - tz - 1) }
})
.collect_ca(PlSmallStr::EMPTY)
},
};
out.into_series()
}
#[doc(hidden)]
pub unsafe fn agg_n_unique(&self, groups: &GroupsType) -> Series {
let values = self.to_physical_repr();
let dtype = values.dtype();
let values = if dtype.contains_objects() {
panic!("{}", polars_err!(opq = unique, dtype));
} else if let Some(ca) = values.try_str() {
ca.as_binary().into_column()
} else if dtype.is_nested() {
encode_rows_unordered(&[values.into_owned().into_column()])
.unwrap()
.into_column()
} else {
values.into_owned().into_column()
};
// Keep the Column for the sort-fallback path. Big groups go through
// `Series::n_unique`, bypassing the amortized hashset.
let col = values.clone();
let values = values.rechunk_to_arrow(CompatLevel::newest());
let values = values.as_ref();
let state = amortized_unique_from_dtype(values.dtype());
struct CloneWrapper(Box<dyn AmortizedUnique>);View on GitHub (pinned to fe841f959e)