polars_core/utils/
series.rs

1use std::rc::Rc;
2
3use crate::prelude::*;
4use crate::series::amortized_iter::AmortSeries;
5
6/// A utility that allocates an [`AmortSeries`]. The applied function can then use that
7/// series container to save heap allocations and swap arrow arrays.
8pub fn with_unstable_series<F, T>(dtype: &DataType, f: F) -> T
9where
10    F: Fn(&mut AmortSeries) -> T,
11{
12    let container = Series::full_null(PlSmallStr::EMPTY, 0, dtype);
13    let mut us = AmortSeries::new(Rc::new(container));
14
15    f(&mut us)
16}
17
18pub fn handle_casting_failures(input: &Series, output: &Series) -> PolarsResult<()> {
19    let failure_mask = !input.is_null() & output.is_null();
20    let failures = input.filter(&failure_mask)?;
21
22    let additional_info = match (input.dtype(), output.dtype()) {
23        (DataType::String, DataType::Date | DataType::Datetime(_, _)) => {
24            "\n\nYou might want to try:\n\
25            - setting `strict=False` to set values that cannot be converted to `null`\n\
26            - using `str.strptime`, `str.to_date`, or `str.to_datetime` and providing a format string"
27        },
28        #[cfg(feature = "dtype-categorical")]
29        (DataType::String, DataType::Enum(_, _)) => {
30            "\n\nEnsure that all values in the input column are present in the categories of the enum datatype."
31        },
32        _ => "",
33    };
34
35    polars_bail!(
36        InvalidOperation:
37        "conversion from `{}` to `{}` failed in column '{}' for {} out of {} values: {}{}",
38        input.dtype(),
39        output.dtype(),
40        output.name(),
41        failures.len(),
42        input.len(),
43        failures.fmt_list(),
44        additional_info,
45    )
46}