{"record":{"id":"490143273dc66ccf","repo":"pola-rs/polars","slug":"data-types-of-values-should-match","errorCode":null,"errorMessage":"data types of values should match","messagePattern":"data types of values should match","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/polars-core/src/series/any_value.rs","lineNumber":24,"sourceCode":"\n#[cfg(feature = \"dtype-categorical\")]\nuse crate::chunked_array::builder::CategoricalChunkedBuilder;\nuse crate::chunked_array::builder::{AnonymousOwnedListBuilder, get_list_builder};\nuse crate::prelude::*;\nuse crate::utils::any_values_to_supertype;\n\nimpl<'a, T: AsRef<[AnyValue<'a>]>> NamedFrom<T, [AnyValue<'a>]> for Series {\n    /// Construct a new [`Series`] from a collection of [`AnyValue`].\n    ///\n    /// # Panics\n    ///\n    /// Panics if the values do not all share the same data type (with the exception\n    /// of [`DataType::Null`], which is always allowed).\n    ///\n    /// [`AnyValue`]: crate::datatypes::AnyValue\n    fn new(name: PlSmallStr, values: T) -> Self {\n        let values = values.as_ref();\n        Series::from_any_values(name, values, true).expect(\"data types of values should match\")\n    }\n}\n\nimpl Series {\n    /// Construct a new [`Series`] from a slice of AnyValues.\n    ///\n    /// The data type of the resulting Series is determined by the `values`\n    /// and the `strict` parameter:\n    /// - If `strict` is `true`, the data type is equal to the data type of the\n    ///   first non-null value. If any other non-null values do not match this\n    ///   data type, an error is raised. If the first non-null value is a\n    ///   decimal the slice is scanned for the maximum precision and scale possible.\n    /// - If `strict` is `false`, the data type is the supertype of the `values`.\n    ///   An error is returned if no supertype can be determined.\n    ///   **WARNING**: A full pass over the values is required to determine the supertype.\n    /// - If no values were passed, the resulting data type is `Null`.\n    pub fn from_any_values(\n        name: PlSmallStr,","sourceCodeStart":6,"sourceCodeEnd":42,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/crates/polars-core/src/series/any_value.rs#L6-L42","documentation":"`Series::new(name, values)` built from `AnyValue` elements requires every value to share one logical data type (Null is always permitted). Internally it calls `Series::from_any_values(..., true)` where `true` means strict, and the Result is unwrapped, so mixed dtypes (e.g. integers and strings in one slice) abort with 'data types of values should match'.","triggerScenarios":"`Series::new(\"x\", &[AnyValue::Int64(1), AnyValue::String(\"a\")])`; collecting AnyValues from heterogeneous sources (JSON arrays of mixed types, CSV rows with inconsistent fields) into one Series.","commonSituations":"Dynamic/JSON data where a field is sometimes numeric and sometimes string; iterating `AnyValue` rows and re-collecting them without normalizing dtype; tests constructing Series from literal slices with a typo in one element.","solutions":["Ensure all AnyValues in the slice share one dtype before construction (cast values to a common type).","Use `Series::from_any_values(name, &values, false)` (strict=false) to get a Result and handle incompatible values instead of panicking.","Use `AnyValue::Null` for missing/mismatched entries, since Null is accepted alongside any dtype.","If the data is genuinely heterogeneous, build a DataFrame with separate Series per dtype or a List dtype."],"exampleFix":"// before\nlet s = Series::new(\"x\", &[AnyValue::Int64(1), AnyValue::String(\"a\")]); // panics\n\n// after\nlet vals = vec![AnyValue::Int64(1), AnyValue::Null]; // normalize to one dtype\nlet s = Series::from_any_values(\"x\".into(), &vals, false).unwrap();","handlingStrategy":"validation","validationCode":"let dtypes: std::collections::HashSet<_> = values.iter().filter(|v| !matches!(v, AnyValue::Null)).map(AnyValue::dtype).collect();\nassert!(dtypes.len() <= 1, \"mixed AnyValue dtypes: {:?}\", dtypes);","typeGuard":"fn homogeneous(values: &[AnyValue]) -> bool {\n    let mut d: Option<DataType> = None;\n    values.iter().all(|v| matches!(v, AnyValue::Null)\n        || d.replace(v.dtype()).map_or(true, |p| p == v.dtype()))\n}","tryCatchPattern":"match Series::from_any_values(name, &values, false) {\n    Ok(s) => s,\n    Err(e) => { /* normalize dtypes and retry */ }\n}","preventionTips":["Normalize AnyValues to a single dtype (Null for gaps) before building a Series.","Use strict=false (from_any_values) to get a Result instead of a panic.","Validate dtype homogeneity when ingesting dynamic data (JSON, CSV)."],"tags":["rust","polars","series","anyvalue","dtype-mismatch"],"backgroundTag":"dtype-mismatch","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"}