{"record":{"id":"4b636fe64717e24d","repo":"pola-rs/polars","slug":"unique-operation-not-supported-for-dtype","errorCode":null,"errorMessage":"`unique` operation not supported for dtype `{}`","messagePattern":"`unique` operation not supported for dtype `(.+?)`","errorType":"panic","errorClass":"InvalidOperation","httpStatus":null,"severity":"error","filePath":"crates/polars-core/src/frame/group_by/aggregations/dispatch.rs","lineNumber":289,"sourceCode":"                            return None;\n                        }\n                        let v = mask.sliced_unchecked(first as usize, len as usize);\n                        let tz = v.trailing_zeros() as IdxSize;\n                        if tz == len { None } else { Some(len - tz - 1) }\n                    })\n                    .collect_ca(PlSmallStr::EMPTY)\n            },\n        };\n\n        out.into_series()\n    }\n\n    #[doc(hidden)]\n    pub unsafe fn agg_n_unique(&self, groups: &GroupsType) -> Series {\n        let values = self.to_physical_repr();\n        let dtype = values.dtype();\n        let values = if dtype.contains_objects() {\n            panic!(\"{}\", polars_err!(opq = unique, dtype));\n        } else if let Some(ca) = values.try_str() {\n            ca.as_binary().into_column()\n        } else if dtype.is_nested() {\n            encode_rows_unordered(&[values.into_owned().into_column()])\n                .unwrap()\n                .into_column()\n        } else {\n            values.into_owned().into_column()\n        };\n\n        // Keep the Column for the sort-fallback path. Big groups go through\n        // `Series::n_unique`, bypassing the amortized hashset.\n        let col = values.clone();\n        let values = values.rechunk_to_arrow(CompatLevel::newest());\n        let values = values.as_ref();\n        let state = amortized_unique_from_dtype(values.dtype());\n\n        struct CloneWrapper(Box<dyn AmortizedUnique>);","sourceCodeStart":271,"sourceCodeEnd":307,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/crates/polars-core/src/frame/group_by/aggregations/dispatch.rs#L271-L307","documentation":"`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()`.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\ndf.group_by([\"k\"])?.agg([col(\"obj_col\").n_unique()])?;\n\n// after\nlet cols: Vec<_> = df.get_column_names()\n    .into_iter()\n    .filter(|n| !df.column(n).unwrap().dtype().contains_objects())\n    .collect();\ndf.group_by([\"k\"])?.agg(cols.iter().map(|n| col(*n).n_unique()).collect::<Vec<_>>())?;","handlingStrategy":"type-guard","validationCode":"if df.column(\"obj_col\")?.dtype().contains_objects() {\n    // skip n_unique on this column\n}","typeGuard":"fn supports_n_unique(s: &Series) -> bool {\n    !s.dtype().contains_objects()\n}","tryCatchPattern":"// panic-based, not catchable in stable Rust; guard instead:\nfor name in cols {\n    if supports_n_unique(df.column(name)?) {\n        aggs.push(col(name).n_unique());\n    }\n}","preventionTips":["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."],"tags":["rust","polars","group-by","object-dtype","unsupported-dtype"],"backgroundTag":"unsupported-dtype","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}