pola-rs/polars · error
data types of values should match
Error message
data types of values should match
What it means
`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'.
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.
Example fix
// before
let s = Series::new("x", &[AnyValue::Int64(1), AnyValue::String("a")]); // panics
// after
let vals = vec![AnyValue::Int64(1), AnyValue::Null]; // normalize to one dtype
let s = Series::from_any_values("x".into(), &vals, false).unwrap(); Defensive patterns
Strategy: validation
Validate before calling
let dtypes: std::collections::HashSet<_> = values.iter().filter(|v| !matches!(v, AnyValue::Null)).map(AnyValue::dtype).collect();
assert!(dtypes.len() <= 1, "mixed AnyValue dtypes: {:?}", dtypes); Type guard
fn homogeneous(values: &[AnyValue]) -> bool {
let mut d: Option<DataType> = None;
values.iter().all(|v| matches!(v, AnyValue::Null)
|| d.replace(v.dtype()).map_or(true, |p| p == v.dtype()))
} Try / catch
match Series::from_any_values(name, &values, false) {
Ok(s) => s,
Err(e) => { /* normalize dtypes and retry */ }
} Prevention
- 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).
When it happens
Trigger: `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.
Common situations: 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.
Related errors
- dtype is unknown; consider supplying data-types for all…
- scalar ordering for mixed dtypes
- {0}
- activate dtype
- activate dtype-categorical to convert dictionary arrays
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/490143273dc66ccf.
Report an issue: GitHub.
Appendix: source
Thrown at crates/polars-core/src/series/any_value.rs:24
#[cfg(feature = "dtype-categorical")]
use crate::chunked_array::builder::CategoricalChunkedBuilder;
use crate::chunked_array::builder::{AnonymousOwnedListBuilder, get_list_builder};
use crate::prelude::*;
use crate::utils::any_values_to_supertype;
impl<'a, T: AsRef<[AnyValue<'a>]>> NamedFrom<T, [AnyValue<'a>]> for Series {
/// Construct a new [`Series`] from a collection of [`AnyValue`].
///
/// # Panics
///
/// Panics if the values do not all share the same data type (with the exception
/// of [`DataType::Null`], which is always allowed).
///
/// [`AnyValue`]: crate::datatypes::AnyValue
fn new(name: PlSmallStr, values: T) -> Self {
let values = values.as_ref();
Series::from_any_values(name, values, true).expect("data types of values should match")
}
}
impl Series {
/// Construct a new [`Series`] from a slice of AnyValues.
///
/// The data type of the resulting Series is determined by the `values`
/// and the `strict` parameter:
/// - If `strict` is `true`, the data type is equal to the data type of the
/// first non-null value. If any other non-null values do not match this
/// data type, an error is raised. If the first non-null value is a
/// decimal the slice is scanned for the maximum precision and scale possible.
/// - If `strict` is `false`, the data type is the supertype of the `values`.
/// An error is returned if no supertype can be determined.
/// **WARNING**: A full pass over the values is required to determine the supertype.
/// - If no values were passed, the resulting data type is `Null`.
pub fn from_any_values(
name: PlSmallStr,View on GitHub (pinned to fe841f959e)