Skip to main content

polars_core/series/
mod.rs

1#![allow(unsafe_op_in_unsafe_fn)]
2//! Type agnostic columnar data structure.
3use crate::chunked_array::flags::StatisticsFlags;
4pub use crate::prelude::ChunkCompareEq;
5use crate::prelude::*;
6use crate::{HEAD_DEFAULT_LENGTH, TAIL_DEFAULT_LENGTH};
7
8macro_rules! invalid_operation_panic {
9    ($op:ident, $s:expr) => {
10        panic!(
11            "`{}` operation not supported for dtype `{}`",
12            stringify!($op),
13            $s._dtype()
14        )
15    };
16}
17
18pub mod amortized_iter;
19mod any_value;
20pub mod arithmetic;
21pub mod arrow_export;
22pub mod builder;
23
24mod comparison;
25mod from;
26pub mod implementations;
27pub(crate) mod iterator;
28pub mod ops;
29#[cfg(feature = "proptest")]
30pub mod proptest;
31mod series_trait;
32
33use std::borrow::Cow;
34use std::hash::{Hash, Hasher};
35use std::ops::Deref;
36
37pub use from::*;
38pub use iterator::SeriesIter;
39use num_traits::NumCast;
40use polars_arrow::compute::aggregate::estimated_bytes_size;
41use polars_error::feature_gated;
42use polars_utils::broadcast::BroadcastLength;
43use polars_utils::float::IsFloat;
44use polars_utils::slice_enum::Slice;
45pub use series_trait::{IsSorted, *};
46
47use crate::chunked_array::cast::CastOptions;
48use crate::runtime::RAYON;
49#[cfg(feature = "zip_with")]
50use crate::series::arithmetic::coerce_lhs_rhs;
51use crate::utils::{Wrap, handle_casting_failures, materialize_dyn_int};
52
53/// # Series
54/// The columnar data type for a DataFrame.
55///
56/// Most of the available functions are defined in the [SeriesTrait trait](crate::series::SeriesTrait).
57///
58/// The `Series` struct consists
59/// of typed [ChunkedArray]'s. To quickly cast
60/// a `Series` to a `ChunkedArray` you can call the method with the name of the type:
61///
62/// ```
63/// # use polars_core::prelude::*;
64/// let s: Series = [1, 2, 3].iter().collect();
65/// // Quickly obtain the ChunkedArray wrapped by the Series.
66/// let chunked_array = s.i32().unwrap();
67/// ```
68///
69/// ## Arithmetic
70///
71/// You can do standard arithmetic on series.
72/// ```
73/// # use polars_core::prelude::*;
74/// let s = Series::new("a".into(), [1 , 2, 3]);
75/// let out_add = &s + &s;
76/// let out_sub = &s - &s;
77/// let out_div = &s / &s;
78/// let out_mul = &s * &s;
79/// ```
80///
81/// Or with series and numbers.
82///
83/// ```
84/// # use polars_core::prelude::*;
85/// let s: Series = (1..3).collect();
86/// let out_add_one = &s + 1;
87/// let out_multiply = &s * 10;
88///
89/// // Could not overload left hand side operator.
90/// let out_divide = 1.div(&s);
91/// let out_add = 1.add(&s);
92/// let out_subtract = 1.sub(&s);
93/// let out_multiply = 1.mul(&s);
94/// ```
95///
96/// ## Comparison
97/// You can obtain boolean mask by comparing series.
98///
99/// ```
100/// # use polars_core::prelude::*;
101/// let s = Series::new("dollars".into(), &[1, 2, 3]);
102/// let mask = s.equal(1).unwrap();
103/// let valid = [true, false, false].iter();
104/// assert!(mask
105///     .iter()
106///     .map(|opt_bool| opt_bool.unwrap()) // option, because series can be null
107///     .zip(valid)
108///     .all(|(a, b)| a == *b))
109/// ```
110///
111/// See all the comparison operators in the [ChunkCompareEq trait](crate::chunked_array::ops::ChunkCompareEq) and
112/// [ChunkCompareIneq trait](crate::chunked_array::ops::ChunkCompareIneq).
113///
114/// ## Iterators
115/// The Series variants contain differently typed [ChunkedArray]s.
116/// These structs can be turned into iterators, making it possible to use any function/ closure you want
117/// on a Series.
118///
119/// These iterators return an `Option<T>` because the values of a series may be null.
120///
121/// ```
122/// use polars_core::prelude::*;
123/// let pi = 3.14;
124/// let s = Series::new("angle".into(), [2f32 * pi, pi, 1.5 * pi].as_ref());
125/// let s_cos: Series = s.f32()
126///                     .expect("series was not an f32 dtype")
127///                     .iter()
128///                     .map(|opt_angle| opt_angle.map(|angle| angle.cos()))
129///                     .collect();
130/// ```
131///
132/// ## Creation
133/// Series can be created from different data structures. Below we'll show a few ways we can create
134/// a Series object.
135///
136/// ```
137/// # use polars_core::prelude::*;
138/// // Series can be created from Vec's, slices and arrays
139/// Series::new("boolean series".into(), &[true, false, true]);
140/// Series::new("int series".into(), &[1, 2, 3]);
141/// // And can be nullable
142/// Series::new("got nulls".into(), &[Some(1), None, Some(2)]);
143///
144/// // Series can also be collected from iterators
145/// let from_iter: Series = (0..10)
146///     .into_iter()
147///     .collect();
148///
149/// ```
150#[derive(Clone)]
151#[must_use]
152pub struct Series(pub Arc<dyn SeriesTrait>);
153
154impl PartialEq for Wrap<Series> {
155    fn eq(&self, other: &Self) -> bool {
156        self.0.equals_missing(other)
157    }
158}
159
160impl Eq for Wrap<Series> {}
161
162impl Hash for Wrap<Series> {
163    fn hash<H: Hasher>(&self, state: &mut H) {
164        self.dtype().hash(state);
165        self.len().hash(state);
166
167        for av in self.iter() {
168            av.hash(state);
169        }
170    }
171}
172
173impl Series {
174    /// Create a new empty Series.
175    pub fn new_empty(name: PlSmallStr, dtype: &DataType) -> Series {
176        Series::full_null(name, 0, dtype)
177    }
178
179    pub fn clear(&self) -> Series {
180        if self.is_empty() {
181            self.clone()
182        } else {
183            match self.dtype() {
184                #[cfg(feature = "object")]
185                DataType::Object(_) => self
186                    .take(&ChunkedArray::<IdxType>::new_vec(PlSmallStr::EMPTY, vec![]))
187                    .unwrap(),
188                dt => Series::new_empty(self.name().clone(), dt),
189            }
190        }
191    }
192
193    #[doc(hidden)]
194    pub fn _get_inner_mut(&mut self) -> &mut dyn SeriesTrait {
195        if Arc::weak_count(&self.0) + Arc::strong_count(&self.0) != 1 {
196            self.0 = self.0.clone_inner();
197        }
198        Arc::get_mut(&mut self.0).expect("implementation error")
199    }
200
201    /// Take or clone a owned copy of the inner [`ChunkedArray`].
202    pub fn take_inner<T: PolarsPhysicalType>(self) -> ChunkedArray<T> {
203        let arc_any = self.0.as_arc_any();
204        let downcast = arc_any
205            .downcast::<implementations::SeriesWrap<ChunkedArray<T>>>()
206            .unwrap();
207
208        match Arc::try_unwrap(downcast) {
209            Ok(ca) => ca.0,
210            Err(ca) => ca.as_ref().as_ref().clone(),
211        }
212    }
213
214    /// Returns a reference to the Arrow ArrayRef
215    #[inline]
216    pub fn array_ref(&self, chunk_idx: usize) -> &ArrayRef {
217        &self.chunks()[chunk_idx] as &ArrayRef
218    }
219
220    /// # Safety
221    /// The caller must ensure the length and the data types of `ArrayRef` does not change.
222    /// And that the null_count is updated (e.g. with a `compute_len()`)
223    pub unsafe fn chunks_mut(&mut self) -> &mut Vec<ArrayRef> {
224        #[allow(unused_mut)]
225        let mut ca = self._get_inner_mut();
226        ca.chunks_mut()
227    }
228
229    pub fn into_chunks(mut self) -> Vec<ArrayRef> {
230        let ca = self._get_inner_mut();
231        let chunks = std::mem::take(unsafe { ca.chunks_mut() });
232        ca.compute_len();
233        chunks
234    }
235
236    // TODO! this probably can now be removed, now we don't have special case for structs.
237    pub fn select_chunk(&self, i: usize) -> Self {
238        let mut new = self.clear();
239        let mut flags = self.get_flags();
240
241        use StatisticsFlags as F;
242        flags &= F::IS_SORTED_ANY | F::CAN_FAST_EXPLODE_LIST;
243
244        // Assign mut so we go through arc only once.
245        let mut_new = new._get_inner_mut();
246        let chunks = unsafe { mut_new.chunks_mut() };
247        let chunk = self.chunks()[i].clone();
248        chunks.clear();
249        chunks.push(chunk);
250        mut_new.compute_len();
251        mut_new._set_flags(flags);
252        new
253    }
254
255    pub fn is_sorted_flag(&self) -> IsSorted {
256        if self.len() <= 1 {
257            return IsSorted::Ascending;
258        }
259        self.get_flags().is_sorted()
260    }
261
262    pub fn set_sorted_flag(&mut self, sorted: IsSorted) {
263        let mut flags = self.get_flags();
264        flags.set_sorted(sorted);
265        self.set_flags(flags);
266    }
267
268    pub(crate) fn clear_flags(&mut self) {
269        self.set_flags(StatisticsFlags::empty());
270    }
271    pub fn get_flags(&self) -> StatisticsFlags {
272        self.0._get_flags()
273    }
274
275    pub(crate) fn set_flags(&mut self, flags: StatisticsFlags) {
276        self._get_inner_mut()._set_flags(flags)
277    }
278
279    pub fn into_frame(self) -> DataFrame {
280        // SAFETY: A single-column dataframe cannot have length mismatches or duplicate names
281        unsafe { DataFrame::new_unchecked(self.len(), vec![self.into()]) }
282    }
283
284    /// Rename series.
285    pub fn rename(&mut self, name: PlSmallStr) -> &mut Series {
286        self._get_inner_mut().rename(name);
287        self
288    }
289
290    /// Return this Series with a new name.
291    pub fn with_name(mut self, name: PlSmallStr) -> Series {
292        self.rename(name);
293        self
294    }
295
296    pub fn from_arrow_chunks(name: PlSmallStr, arrays: Vec<ArrayRef>) -> PolarsResult<Series> {
297        Self::try_from((name, arrays))
298    }
299
300    pub fn from_arrow(name: PlSmallStr, array: ArrayRef) -> PolarsResult<Series> {
301        Self::try_from((name, array))
302    }
303
304    /// Shrink the capacity of this array to fit its length.
305    pub fn shrink_to_fit(&mut self) {
306        self._get_inner_mut().shrink_to_fit()
307    }
308
309    /// Append in place. This is done by adding the chunks of `other` to this [`Series`].
310    ///
311    /// See [`ChunkedArray::append`] and [`ChunkedArray::extend`].
312    pub fn append(&mut self, other: &Series) -> PolarsResult<&mut Self> {
313        let must_cast = other.dtype().matches_schema_type(self.dtype())?;
314        if must_cast {
315            let other = other.cast(self.dtype())?;
316            self.append_owned(other)?;
317        } else {
318            self._get_inner_mut().append(other)?;
319        }
320        Ok(self)
321    }
322
323    /// Append in place. This is done by adding the chunks of `other` to this [`Series`].
324    ///
325    /// See [`ChunkedArray::append_owned`] and [`ChunkedArray::extend`].
326    pub fn append_owned(&mut self, other: Series) -> PolarsResult<&mut Self> {
327        let must_cast = other.dtype().matches_schema_type(self.dtype())?;
328        if must_cast {
329            let other = other.cast(self.dtype())?;
330            self._get_inner_mut().append_owned(other)?;
331        } else {
332            self._get_inner_mut().append_owned(other)?;
333        }
334        Ok(self)
335    }
336
337    /// Redo a length and null_count compute
338    pub fn compute_len(&mut self) {
339        self._get_inner_mut().compute_len()
340    }
341
342    /// Extend the memory backed by this array with the values from `other`.
343    ///
344    /// See [`ChunkedArray::extend`] and [`ChunkedArray::append`].
345    pub fn extend(&mut self, other: &Series) -> PolarsResult<&mut Self> {
346        let must_cast = other.dtype().matches_schema_type(self.dtype())?;
347        if must_cast {
348            let other = other.cast(self.dtype())?;
349            self._get_inner_mut().extend(&other)?;
350        } else {
351            self._get_inner_mut().extend(other)?;
352        }
353        Ok(self)
354    }
355
356    /// Returns a series with the given length.
357    ///
358    /// Errors if this series' length is not 1 and also not equal to the requested length.
359    pub fn broadcast_to(&self, length: usize) -> PolarsResult<Cow<'_, Self>> {
360        let len = self.len();
361        if len == length {
362            Ok(Cow::Borrowed(self))
363        } else if len == 1 {
364            Ok(Cow::Owned(self.new_from_index(0, length)))
365        } else {
366            polars_bail!(
367                ShapeMismatch: "can't broadcast Series '{}' of length {len} to length {length}",
368                self.name()
369            );
370        }
371    }
372
373    /// See broadcast_to.
374    pub fn broadcast_in_place_to(&mut self, length: usize) -> PolarsResult<()> {
375        if let Cow::Owned(new) = self.broadcast_to(length)? {
376            *self = new;
377        }
378        Ok(())
379    }
380
381    /// See broadcast_to.
382    pub fn broadcast_owned_to(mut self, length: usize) -> PolarsResult<Self> {
383        self.broadcast_in_place_to(length)?;
384        Ok(self)
385    }
386
387    /// Sort the series with specific options.
388    ///
389    /// # Example
390    ///
391    /// ```rust
392    /// # use polars_core::prelude::*;
393    /// # fn main() -> PolarsResult<()> {
394    /// let s = Series::new("foo".into(), [2, 1, 3]);
395    /// let sorted = s.sort(SortOptions::default())?;
396    /// assert_eq!(sorted, Series::new("foo".into(), [1, 2, 3]));
397    /// # Ok(())
398    /// }
399    /// ```
400    ///
401    /// See [`SortOptions`] for more options.
402    pub fn sort(&self, sort_options: SortOptions) -> PolarsResult<Self> {
403        self.sort_with(sort_options)
404    }
405
406    /// Only implemented for numeric types
407    pub fn as_single_ptr(&mut self) -> PolarsResult<usize> {
408        self._get_inner_mut().as_single_ptr()
409    }
410
411    pub fn cast(&self, dtype: &DataType) -> PolarsResult<Self> {
412        self.cast_with_options(dtype, CastOptions::NonStrict)
413    }
414
415    /// Cast [`Series`] to another [`DataType`].
416    pub fn cast_with_options(&self, dtype: &DataType, options: CastOptions) -> PolarsResult<Self> {
417        let slf = self
418            .trim_lists_to_normalized_offsets()
419            .map_or(Cow::Borrowed(self), Cow::Owned);
420        let slf = slf.propagate_nulls().map_or(slf, Cow::Owned);
421
422        use DataType as D;
423        let do_clone = match dtype {
424            D::Unknown(UnknownKind::Any) => true,
425            D::Unknown(UnknownKind::Int(_)) if slf.dtype().is_integer() => true,
426            D::Unknown(UnknownKind::Float) if slf.dtype().is_float() => true,
427            D::Unknown(UnknownKind::Str)
428                if slf.dtype().is_string() | slf.dtype().is_categorical() =>
429            {
430                true
431            },
432            dt if (dt.is_primitive() || dt.is_extension()) && dt == slf.dtype() => true,
433            _ => false,
434        };
435
436        if do_clone {
437            return Ok(slf.into_owned());
438        }
439
440        pub fn cast_dtype(dtype: &DataType) -> Option<DataType> {
441            match dtype {
442                D::Unknown(UnknownKind::Int(v)) => Some(materialize_dyn_int(*v).dtype()),
443                D::Unknown(UnknownKind::Float) => Some(DataType::Float64),
444                D::Unknown(UnknownKind::Str) => Some(DataType::String),
445                // Best leave as is.
446                D::List(inner) => cast_dtype(inner.as_ref()).map(Box::new).map(D::List),
447                #[cfg(feature = "dtype-struct")]
448                D::Struct(fields) => {
449                    // @NOTE: We only allocate if we really need to.
450
451                    let mut field_iter = fields.iter().enumerate();
452                    let mut new_fields = loop {
453                        let (i, field) = field_iter.next()?;
454
455                        if let Some(dtype) = cast_dtype(&field.dtype) {
456                            let mut new_fields = Vec::with_capacity(fields.len());
457                            new_fields.extend(fields.iter().take(i).cloned());
458                            new_fields.push(Field {
459                                name: field.name.clone(),
460                                dtype,
461                            });
462                            break new_fields;
463                        }
464                    };
465
466                    new_fields.extend(fields.iter().skip(new_fields.len()).cloned().map(|field| {
467                        let dtype = cast_dtype(&field.dtype).unwrap_or(field.dtype);
468                        Field {
469                            name: field.name,
470                            dtype,
471                        }
472                    }));
473
474                    Some(D::Struct(new_fields))
475                },
476                _ => None,
477            }
478        }
479
480        let mut casted = cast_dtype(dtype);
481        if dtype.is_list() && dtype.inner_dtype().is_some_and(|dt| dt.is_null()) {
482            if let Some(from_inner_dtype) = slf.dtype().inner_dtype() {
483                casted = Some(DataType::List(Box::new(from_inner_dtype.clone())));
484            }
485        }
486        let dtype = match casted {
487            None => dtype,
488            Some(ref dtype) => dtype,
489        };
490
491        // Always allow casting all nulls to other all nulls.
492        let len = slf.len();
493        if slf.null_count() == len {
494            return Ok(Series::full_null(slf.name().clone(), len, dtype));
495        }
496
497        let new_options = match options {
498            // Strictness is handled on this level to improve error messages, if not nested.
499            // Nested types could hide cast errors, so have to be done internally.
500            CastOptions::Strict if !dtype.is_nested() => CastOptions::NonStrict,
501            opt => opt,
502        };
503
504        let out = slf.0.cast(dtype, new_options)?;
505        if options.is_strict() {
506            handle_casting_failures(slf.as_ref(), &out)?;
507        }
508        Ok(out)
509    }
510
511    /// Cast from physical to logical types without any checks on the validity of the cast.
512    ///
513    /// # Safety
514    ///
515    /// This can lead to invalid memory access in downstream code.
516    pub unsafe fn cast_unchecked(&self, dtype: &DataType) -> PolarsResult<Self> {
517        match self.dtype() {
518            #[cfg(feature = "dtype-struct")]
519            DataType::Struct(_) => self.struct_().unwrap().cast_unchecked(dtype),
520            DataType::List(_) => self.list().unwrap().cast_unchecked(dtype),
521            dt if dt.is_primitive_numeric() => {
522                with_match_physical_numeric_polars_type!(dt, |$T| {
523                    let ca: &ChunkedArray<$T> = self.as_ref().as_ref().as_ref();
524                        ca.cast_unchecked(dtype)
525                })
526            },
527            DataType::Binary => self.binary().unwrap().cast_unchecked(dtype),
528            _ => self.cast_with_options(dtype, CastOptions::Overflowing),
529        }
530    }
531
532    /// Convert a non-logical series back into a logical series without casting.
533    ///
534    /// # Safety
535    ///
536    /// Payloads must be safe to read as `dtype`: categorical codes in range for every
537    /// non-null slot, and Maps satisfying the `MapChunked` storage safety contract. Null
538    /// Map rows may span entries, and those entries may themselves be null; they are left
539    /// alone. Null entries or keys in live rows are errors. Unsafe payloads can cause
540    /// invalid memory access downstream.
541    ///
542    /// # Key uniqueness
543    /// Not required for safety. Whole-row transformations preserve existing uniqueness;
544    /// key-changing transformations must use validated construction.
545    pub unsafe fn from_physical_unchecked(&self, dtype: &DataType) -> PolarsResult<Self> {
546        debug_assert!(!self.dtype().is_logical(), "{:?}", self.dtype());
547
548        if self.dtype() == dtype {
549            return Ok(self.clone());
550        }
551
552        use DataType as D;
553        match (self.dtype(), dtype) {
554            #[cfg(feature = "dtype-decimal")]
555            (D::Int128, D::Decimal(precision, scale)) => {
556                let ca = self.i128().unwrap();
557                Ok(ca
558                    .clone()
559                    .into_decimal_unchecked(*precision, *scale)
560                    .into_series())
561            },
562
563            #[cfg(feature = "dtype-categorical")]
564            (phys, D::Categorical(cats, _)) if &cats.physical().dtype() == phys => {
565                with_match_categorical_physical_type!(cats.physical(), |$C| {
566                    type CA = ChunkedArray<<$C as PolarsCategoricalType>::PolarsPhysical>;
567                    let ca = self.as_ref().as_any().downcast_ref::<CA>().unwrap();
568                    Ok(CategoricalChunked::<$C>::from_cats_and_dtype_unchecked(
569                        ca.clone(),
570                        dtype.clone(),
571                    )
572                    .into_series())
573                })
574            },
575            #[cfg(feature = "dtype-categorical")]
576            (phys, D::Enum(fcats, _)) if &fcats.physical().dtype() == phys => {
577                with_match_categorical_physical_type!(fcats.physical(), |$C| {
578                    type CA = ChunkedArray<<$C as PolarsCategoricalType>::PolarsPhysical>;
579                    let ca = self.as_ref().as_any().downcast_ref::<CA>().unwrap();
580                    Ok(CategoricalChunked::<$C>::from_cats_and_dtype_unchecked(
581                        ca.clone(),
582                        dtype.clone(),
583                    )
584                    .into_series())
585                })
586            },
587
588            // Arrow `LargeBinary` arrays are read into a series as `Binary`.
589            (D::Binary, D::BinaryOffset) => self.cast(&D::BinaryOffset),
590
591            (D::Int32, D::Date) => feature_gated!("dtype-date", Ok(self.clone().into_date())),
592            (D::Int64, D::Datetime(tu, tz)) => feature_gated!(
593                "dtype-datetime",
594                Ok(self.clone().into_datetime(*tu, tz.clone()))
595            ),
596            (D::Int64, D::Duration(tu)) => {
597                feature_gated!("dtype-duration", Ok(self.clone().into_duration(*tu)))
598            },
599            (D::Int64, D::Time) => feature_gated!("dtype-time", Ok(self.clone().into_time())),
600
601            (D::List(_), D::List(to)) => unsafe {
602                self.list()
603                    .unwrap()
604                    .from_physical_unchecked(to.as_ref().clone())
605                    .map(|ca| ca.into_series())
606            },
607            #[cfg(feature = "dtype-array")]
608            (D::Array(_, lw), D::Array(to, rw)) if lw == rw => unsafe {
609                self.array()
610                    .unwrap()
611                    .from_physical_unchecked(to.as_ref().clone())
612                    .map(|ca| ca.into_series())
613            },
614            #[cfg(feature = "dtype-struct")]
615            (D::Struct(_), D::Struct(to)) => unsafe {
616                self.struct_()
617                    .unwrap()
618                    .from_physical_unchecked(to.as_slice())
619                    .map(|ca| ca.into_series())
620            },
621
622            #[cfg(feature = "dtype-map")]
623            (D::List(_), D::Map(_, _)) => {
624                use crate::chunked_array::logical::ensure_live_entries_non_null;
625
626                let storage = self.from_physical_unchecked(&dtype.map_storage_dtype().unwrap())?;
627                // Nulls that propagation left under null rows are legal; only live rows
628                // must own no null entry or key.
629                ensure_live_entries_non_null(storage.list().unwrap())?;
630                Ok(MapChunked::from_storage_unchecked(dtype.clone(), storage).into_series())
631            },
632            #[cfg(feature = "dtype-extension")]
633            (_, D::Extension(typ, storage)) => {
634                let storage_series = self.from_physical_unchecked(storage.as_ref())?;
635                let ext = ExtensionChunked::from_storage(typ.clone(), storage_series);
636                Ok(ext.into_series())
637            },
638
639            _ => panic!("invalid from_physical({dtype:?}) for {:?}", self.dtype()),
640        }
641    }
642
643    #[cfg(feature = "dtype-extension")]
644    pub fn into_extension(self, typ: ExtensionTypeInstance) -> Series {
645        assert!(!self.dtype().is_extension());
646        let ext = ExtensionChunked::from_storage(typ, self);
647        ext.into_series()
648    }
649
650    /// Cast numerical types to f64, and keep floats as is.
651    pub fn to_float(&self) -> PolarsResult<Series> {
652        match self.dtype() {
653            DataType::Float32 | DataType::Float64 => Ok(self.clone()),
654            _ => self.cast_with_options(&DataType::Float64, CastOptions::Overflowing),
655        }
656    }
657
658    /// Get the sum of the Series as a `Scalar`.
659    /// Returns a `Scalar` with a zeroed value if self is an empty numeric series.
660    ///
661    /// If the [`DataType`] is one of `{Int8, UInt8, Int16, UInt16}` the sum is
662    /// computed in an `Int64` accumulator and the result is returned as `Int64`
663    /// to prevent overflow issues.
664    pub fn sum<T>(&self) -> PolarsResult<T>
665    where
666        T: NumCast + IsFloat,
667    {
668        let sum = self.sum_reduce()?;
669        let sum = sum.value().extract().unwrap();
670        Ok(sum)
671    }
672
673    /// Returns the minimum value in the array, according to the natural order.
674    /// Returns an option because the array is nullable.
675    pub fn min<T>(&self) -> PolarsResult<Option<T>>
676    where
677        T: NumCast + IsFloat,
678    {
679        let min = self.min_reduce()?;
680        let min = min.value().extract::<T>();
681        Ok(min)
682    }
683
684    /// Returns the maximum value in the array, according to the natural order.
685    /// Returns an option because the array is nullable.
686    pub fn max<T>(&self) -> PolarsResult<Option<T>>
687    where
688        T: NumCast + IsFloat,
689    {
690        let max = self.max_reduce()?;
691        let max = max.value().extract::<T>();
692        Ok(max)
693    }
694
695    /// Explode a list Series. This expands every item to a new row..
696    pub fn explode(&self, options: ExplodeOptions) -> PolarsResult<Series> {
697        match self.dtype() {
698            DataType::List(_) => self.list().unwrap().explode(options),
699            #[cfg(feature = "dtype-array")]
700            DataType::Array(_, _) => self.array().unwrap().explode(options),
701            _ => Ok(self.clone()),
702        }
703    }
704
705    /// Check if numeric value is NaN (note this is different than missing/ null)
706    pub fn is_nan(&self) -> PolarsResult<BooleanChunked> {
707        match self.dtype() {
708            #[cfg(feature = "dtype-f16")]
709            DataType::Float16 => Ok(self.f16().unwrap().is_nan()),
710            DataType::Float32 => Ok(self.f32().unwrap().is_nan()),
711            DataType::Float64 => Ok(self.f64().unwrap().is_nan()),
712            DataType::Null => Ok(BooleanChunked::full_null(self.name().clone(), self.len())),
713            dt if dt.is_primitive_numeric() => {
714                let arr = BooleanArray::full(self.len(), false, ArrowDataType::Boolean)
715                    .with_validity(self.rechunk_validity());
716                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
717            },
718            _ => polars_bail!(opq = is_nan, self.dtype()),
719        }
720    }
721
722    /// Check if numeric value is NaN (note this is different than missing/null)
723    pub fn is_not_nan(&self) -> PolarsResult<BooleanChunked> {
724        match self.dtype() {
725            #[cfg(feature = "dtype-f16")]
726            DataType::Float16 => Ok(self.f16().unwrap().is_not_nan()),
727            DataType::Float32 => Ok(self.f32().unwrap().is_not_nan()),
728            DataType::Float64 => Ok(self.f64().unwrap().is_not_nan()),
729            DataType::Null => Ok(BooleanChunked::full_null(self.name().clone(), self.len())),
730            dt if dt.is_primitive_numeric() => {
731                let arr = BooleanArray::full(self.len(), true, ArrowDataType::Boolean)
732                    .with_validity(self.rechunk_validity());
733                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
734            },
735            _ => polars_bail!(opq = is_not_nan, self.dtype()),
736        }
737    }
738
739    /// Check if numeric value is finite
740    pub fn is_finite(&self) -> PolarsResult<BooleanChunked> {
741        match self.dtype() {
742            #[cfg(feature = "dtype-f16")]
743            DataType::Float16 => Ok(self.f16().unwrap().is_finite()),
744            DataType::Float32 => Ok(self.f32().unwrap().is_finite()),
745            DataType::Float64 => Ok(self.f64().unwrap().is_finite()),
746            DataType::Null => Ok(BooleanChunked::full_null(self.name().clone(), self.len())),
747            dt if dt.is_primitive_numeric() => {
748                let arr = BooleanArray::full(self.len(), true, ArrowDataType::Boolean)
749                    .with_validity(self.rechunk_validity());
750                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
751            },
752            _ => polars_bail!(opq = is_finite, self.dtype()),
753        }
754    }
755
756    /// Check if numeric value is infinite
757    pub fn is_infinite(&self) -> PolarsResult<BooleanChunked> {
758        match self.dtype() {
759            #[cfg(feature = "dtype-f16")]
760            DataType::Float16 => Ok(self.f16().unwrap().is_infinite()),
761            DataType::Float32 => Ok(self.f32().unwrap().is_infinite()),
762            DataType::Float64 => Ok(self.f64().unwrap().is_infinite()),
763            DataType::Null => Ok(BooleanChunked::full_null(self.name().clone(), self.len())),
764            dt if dt.is_primitive_numeric() => {
765                let arr = BooleanArray::full(self.len(), false, ArrowDataType::Boolean)
766                    .with_validity(self.rechunk_validity());
767                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
768            },
769            _ => polars_bail!(opq = is_infinite, self.dtype()),
770        }
771    }
772
773    /// Create a new ChunkedArray with values from self where the mask evaluates `true` and values
774    /// from `other` where the mask evaluates `false`. This function automatically broadcasts unit
775    /// length inputs.
776    #[cfg(feature = "zip_with")]
777    pub fn zip_with(&self, mask: &BooleanChunked, other: &Series) -> PolarsResult<Series> {
778        let (lhs, rhs) = coerce_lhs_rhs(self, other)?;
779        lhs.zip_with_same_type(mask, rhs.as_ref())
780    }
781
782    /// Converts a Series to their physical representation, if they have one,
783    /// otherwise the series is left unchanged.
784    ///
785    /// * Date -> Int32
786    /// * Datetime -> Int64
787    /// * Duration -> Int64
788    /// * Decimal -> Int128
789    /// * Time -> Int64
790    /// * Categorical -> U8/U16/U32
791    /// * List(inner) -> List(physical of inner)
792    /// * Array(inner) -> Array(physical of inner)
793    /// * Struct -> Struct with physical repr of each struct column
794    /// * Extension -> physical of storage type
795    pub fn to_physical_repr(&self) -> Cow<'_, Series> {
796        use DataType::*;
797        match self.dtype() {
798            // NOTE: Don't use cast here, as it might rechunk (if all nulls)
799            // which is not allowed in a phys repr.
800            #[cfg(feature = "dtype-date")]
801            Date => Cow::Owned(self.date().unwrap().phys.clone().into_series()),
802            #[cfg(feature = "dtype-datetime")]
803            Datetime(_, _) => Cow::Owned(self.datetime().unwrap().phys.clone().into_series()),
804            #[cfg(feature = "dtype-duration")]
805            Duration(_) => Cow::Owned(self.duration().unwrap().phys.clone().into_series()),
806            #[cfg(feature = "dtype-time")]
807            Time => Cow::Owned(self.time().unwrap().phys.clone().into_series()),
808            #[cfg(feature = "dtype-categorical")]
809            dt @ (Categorical(_, _) | Enum(_, _)) => {
810                with_match_categorical_physical_type!(dt.cat_physical().unwrap(), |$C| {
811                    let ca = self.cat::<$C>().unwrap();
812                    Cow::Owned(ca.physical().clone().into_series())
813                })
814            },
815            #[cfg(feature = "dtype-decimal")]
816            Decimal(_, _) => Cow::Owned(self.decimal().unwrap().phys.clone().into_series()),
817            List(_) => match self.list().unwrap().to_physical_repr() {
818                Cow::Borrowed(_) => Cow::Borrowed(self),
819                Cow::Owned(ca) => Cow::Owned(ca.into_series()),
820            },
821            #[cfg(feature = "dtype-array")]
822            Array(_, _) => match self.array().unwrap().to_physical_repr() {
823                Cow::Borrowed(_) => Cow::Borrowed(self),
824                Cow::Owned(ca) => Cow::Owned(ca.into_series()),
825            },
826            #[cfg(feature = "dtype-struct")]
827            Struct(_) => match self.struct_().unwrap().to_physical_repr() {
828                Cow::Borrowed(_) => Cow::Borrowed(self),
829                Cow::Owned(ca) => Cow::Owned(ca.into_series()),
830            },
831            #[cfg(feature = "dtype-map")]
832            Map(_, _) => match self.map().unwrap().storage().to_physical_repr() {
833                Cow::Borrowed(storage) => Cow::Owned(storage.clone()),
834                Cow::Owned(storage) => Cow::Owned(storage),
835            },
836            #[cfg(feature = "dtype-extension")]
837            Extension(_, _) => self.ext().unwrap().storage().to_physical_repr(),
838            _ => Cow::Borrowed(self),
839        }
840    }
841
842    /// If the Series is an Extension type, return its storage Series.
843    /// Otherwise, return itself.
844    pub fn to_storage(&self) -> &Series {
845        #[cfg(feature = "dtype-extension")]
846        {
847            if let DataType::Extension(_, _) = self.dtype() {
848                return self.ext().unwrap().storage();
849            }
850        }
851        self
852    }
853
854    /// Traverse and collect every nth element in a new array.
855    pub fn gather_every(&self, n: usize, offset: usize) -> PolarsResult<Series> {
856        polars_ensure!(n > 0, ComputeError: "cannot perform gather every for `n=0`");
857        let idx = ((offset as IdxSize)..self.len() as IdxSize)
858            .step_by(n)
859            .collect_ca(PlSmallStr::EMPTY);
860        // SAFETY: we stay in-bounds.
861        Ok(unsafe { self.take_unchecked(&idx) })
862    }
863
864    #[cfg(feature = "dot_product")]
865    pub fn dot(&self, other: &Series) -> PolarsResult<f64> {
866        std::ops::Mul::mul(self, other)?.sum::<f64>()
867    }
868
869    /// Get the sum of the [`ChunkedArray`] as a `Scalar`.
870    /// Returns a `Scalar` with a single zeroed value if self is an empty numeric series.
871    ///
872    /// If the [`DataType`] is one of `{Int8, UInt8, Int16, UInt16}` the sum is
873    /// computed in an `Int64` accumulator and the result is returned as `Int64`
874    /// to prevent overflow issues.
875    pub fn sum_reduce(&self) -> PolarsResult<Scalar> {
876        self.0.sum_reduce()
877    }
878
879    /// Get the mean of the Series as a new Series of length 1.
880    /// Returns a Series with a single null entry if self is an empty numeric series.
881    pub fn mean_reduce(&self) -> PolarsResult<Scalar> {
882        self.0.mean_reduce()
883    }
884
885    /// Get the product of an array.
886    ///
887    /// If the [`DataType`] is one of `{Int8, UInt8, Int16, UInt16}` the `Series` is
888    /// first cast to `Int64` to prevent overflow issues.
889    pub fn product(&self) -> PolarsResult<Scalar> {
890        #[cfg(feature = "product")]
891        {
892            use DataType::*;
893            match self.dtype() {
894                Boolean => self.cast(&DataType::Int64).unwrap().product(),
895                Int8 | UInt8 | Int16 | UInt16 | Int32 | UInt32 => {
896                    let s = self.cast(&Int64).unwrap();
897                    s.product()
898                },
899                Int64 => Ok(self.i64().unwrap().prod_reduce()),
900                UInt64 => Ok(self.u64().unwrap().prod_reduce()),
901                #[cfg(feature = "dtype-i128")]
902                Int128 => Ok(self.i128().unwrap().prod_reduce()),
903                #[cfg(feature = "dtype-u128")]
904                UInt128 => Ok(self.u128().unwrap().prod_reduce()),
905                #[cfg(feature = "dtype-f16")]
906                Float16 => Ok(self.f16().unwrap().prod_reduce()),
907                Float32 => Ok(self.f32().unwrap().prod_reduce()),
908                Float64 => Ok(self.f64().unwrap().prod_reduce()),
909                #[cfg(feature = "dtype-decimal")]
910                Decimal(..) => Ok(self.decimal().unwrap().prod_reduce()),
911                dt => {
912                    polars_bail!(InvalidOperation: "`product` operation not supported for dtype `{dt}`")
913                },
914            }
915        }
916        #[cfg(not(feature = "product"))]
917        {
918            panic!("activate 'product' feature")
919        }
920    }
921
922    /// Cast throws an error if conversion had overflows
923    pub fn strict_cast(&self, dtype: &DataType) -> PolarsResult<Series> {
924        self.cast_with_options(dtype, CastOptions::Strict)
925    }
926
927    /// Cast just the (possibly nested) time units to those at the same positions in `dtype`,
928    /// leaving any other differences to the caller; values that overflow raise if `strict`,
929    /// else become null.
930    pub fn cast_time_units_like(&self, dtype: &DataType, strict: bool) -> PolarsResult<Series> {
931        if !self.dtype().contains_time_units() {
932            return Ok(self.clone());
933        }
934        let mut target = self.dtype().clone();
935        target.adopt_time_units_from(dtype);
936        if &target == self.dtype() {
937            return Ok(self.clone());
938        }
939        let options = if strict {
940            CastOptions::Strict
941        } else {
942            CastOptions::NonStrict
943        };
944        self.cast_with_options(&target, options)
945    }
946
947    /// Cast non-strictly, also returning the rows the cast did not represent exactly.
948    ///
949    /// A row is inexact if it became null or does not survive the cast back unchanged. The mask
950    /// is `None` if every row cast exactly.
951    #[doc(hidden)]
952    pub fn _cast_reporting_inexact(
953        &self,
954        dtype: &DataType,
955    ) -> PolarsResult<(Series, Option<BooleanChunked>)> {
956        let casted = self.cast_with_options(dtype, CastOptions::NonStrict)?;
957        // An integer converts to an integer or decimal exactly or not at all, and the non-strict
958        // cast makes the values out of range null. The null counts tell whether any were.
959        if self.dtype().is_integer() && (dtype.is_integer() || dtype.is_decimal()) {
960            if casted.null_count() == self.null_count() {
961                return Ok((casted, None));
962            }
963            let inexact = &casted.is_null() & &self.is_not_null();
964            return Ok((casted, Some(inexact)));
965        }
966        // Null-safe: a cast back that overflows to null must count as inexact.
967        let roundtrip = casted.cast_with_options(self.dtype(), CastOptions::NonStrict)?;
968        let inexact = roundtrip.not_equal_missing(self)?;
969        debug_assert_eq!(inexact.null_count(), 0);
970        Ok((casted, inexact.any().then_some(inexact)))
971    }
972
973    #[cfg(feature = "dtype-decimal")]
974    pub fn into_decimal(self, precision: usize, scale: usize) -> PolarsResult<Series> {
975        match self.dtype() {
976            DataType::Int128 => Ok(self
977                .i128()
978                .unwrap()
979                .clone()
980                .into_decimal(precision, scale)?
981                .into_series()),
982            DataType::Decimal(cur_prec, cur_scale)
983                if scale == *cur_scale && precision >= *cur_prec =>
984            {
985                Ok(self)
986            },
987            dt => panic!("into_decimal({precision:?}, {scale}) not implemented for {dt:?}"),
988        }
989    }
990
991    #[cfg(feature = "dtype-time")]
992    pub fn into_time(self) -> Series {
993        match self.dtype() {
994            DataType::Int64 => self.i64().unwrap().clone().into_time().into_series(),
995            DataType::Time => self
996                .time()
997                .unwrap()
998                .physical()
999                .clone()
1000                .into_time()
1001                .into_series(),
1002            dt => panic!("date not implemented for {dt:?}"),
1003        }
1004    }
1005
1006    pub fn into_date(self) -> Series {
1007        #[cfg(not(feature = "dtype-date"))]
1008        {
1009            panic!("activate feature dtype-date")
1010        }
1011        #[cfg(feature = "dtype-date")]
1012        match self.dtype() {
1013            DataType::Int32 => self.i32().unwrap().clone().into_date().into_series(),
1014            DataType::Date => self
1015                .date()
1016                .unwrap()
1017                .physical()
1018                .clone()
1019                .into_date()
1020                .into_series(),
1021            dt => panic!("date not implemented for {dt:?}"),
1022        }
1023    }
1024
1025    #[allow(unused_variables)]
1026    pub fn into_datetime(self, timeunit: TimeUnit, tz: Option<TimeZone>) -> Series {
1027        #[cfg(not(feature = "dtype-datetime"))]
1028        {
1029            panic!("activate feature dtype-datetime")
1030        }
1031
1032        #[cfg(feature = "dtype-datetime")]
1033        match self.dtype() {
1034            DataType::Int64 => self
1035                .i64()
1036                .unwrap()
1037                .clone()
1038                .into_datetime(timeunit, tz)
1039                .into_series(),
1040            DataType::Datetime(_, _) => self
1041                .datetime()
1042                .unwrap()
1043                .physical()
1044                .clone()
1045                .into_datetime(timeunit, tz)
1046                .into_series(),
1047            dt => panic!("into_datetime not implemented for {dt:?}"),
1048        }
1049    }
1050
1051    #[allow(unused_variables)]
1052    pub fn into_duration(self, timeunit: TimeUnit) -> Series {
1053        #[cfg(not(feature = "dtype-duration"))]
1054        {
1055            panic!("activate feature dtype-duration")
1056        }
1057        #[cfg(feature = "dtype-duration")]
1058        match self.dtype() {
1059            DataType::Int64 => self
1060                .i64()
1061                .unwrap()
1062                .clone()
1063                .into_duration(timeunit)
1064                .into_series(),
1065            DataType::Duration(_) => self
1066                .duration()
1067                .unwrap()
1068                .physical()
1069                .clone()
1070                .into_duration(timeunit)
1071                .into_series(),
1072            dt => panic!("into_duration not implemented for {dt:?}"),
1073        }
1074    }
1075
1076    // used for formatting
1077    pub fn str_value(&self, index: usize) -> PolarsResult<Cow<'_, str>> {
1078        Ok(self.0.get(index)?.str_value())
1079    }
1080    /// Get the head of the Series.
1081    pub fn head(&self, length: Option<usize>) -> Series {
1082        self.slice(Slice::head(length.unwrap_or(HEAD_DEFAULT_LENGTH)))
1083    }
1084
1085    /// Get the tail of the Series.
1086    pub fn tail(&self, length: Option<usize>) -> Series {
1087        self.slice(Slice::tail(length.unwrap_or(TAIL_DEFAULT_LENGTH)))
1088    }
1089
1090    /// Get a zero copy view of the elements `slice` selects.
1091    pub fn slice(&self, slice: impl Into<Slice>) -> Series {
1092        self.0.slice(slice.into())
1093    }
1094
1095    /// Compute the unique elements, but maintain order. This requires more work
1096    /// than a naive [`Series::unique`](SeriesTrait::unique).
1097    pub fn unique_stable(&self) -> PolarsResult<Series> {
1098        let idx = self.arg_unique()?;
1099        // SAFETY: Indices are in bounds.
1100        unsafe { Ok(self.take_unchecked(&idx)) }
1101    }
1102
1103    pub fn try_idx(&self) -> Option<&IdxCa> {
1104        #[cfg(feature = "bigidx")]
1105        {
1106            self.try_u64()
1107        }
1108        #[cfg(not(feature = "bigidx"))]
1109        {
1110            self.try_u32()
1111        }
1112    }
1113
1114    pub fn idx(&self) -> PolarsResult<&IdxCa> {
1115        #[cfg(feature = "bigidx")]
1116        {
1117            self.u64()
1118        }
1119        #[cfg(not(feature = "bigidx"))]
1120        {
1121            self.u32()
1122        }
1123    }
1124
1125    /// Returns an estimation of the total (heap) allocated size of the `Series` in bytes.
1126    ///
1127    /// # Implementation
1128    /// This estimation is the sum of the size of its buffers, validity, including nested arrays.
1129    /// Multiple arrays may share buffers and bitmaps. Therefore, the size of 2 arrays is not the
1130    /// sum of the sizes computed from this function. In particular, [`StructArray`]'s size is an upper bound.
1131    ///
1132    /// When an array is sliced, its allocated size remains constant because the buffer unchanged.
1133    /// However, this function will yield a smaller number. This is because this function returns
1134    /// the visible size of the buffer, not its total capacity.
1135    ///
1136    /// FFI buffers are included in this estimation.
1137    pub fn estimated_size(&self) -> usize {
1138        let mut size = 0;
1139        match self.dtype() {
1140            // TODO @ cat-rework: include mapping size here?
1141            #[cfg(feature = "object")]
1142            DataType::Object(_) => {
1143                let ArrowDataType::FixedSizeBinary(size) = self.chunks()[0].dtype() else {
1144                    unreachable!()
1145                };
1146                // This is only the pointer size in python. So will be a huge underestimation.
1147                return self.len() * *size;
1148            },
1149            _ => {},
1150        }
1151
1152        size += self
1153            .chunks()
1154            .iter()
1155            .map(|arr| estimated_bytes_size(&**arr))
1156            .sum::<usize>();
1157
1158        size
1159    }
1160
1161    pub fn row_encode_unordered(&self) -> PolarsResult<BinaryOffsetChunked> {
1162        row_encode::_get_rows_encoded_ca_unordered(
1163            self.name().clone(),
1164            &[self.clone().into_column()],
1165        )
1166    }
1167
1168    pub fn row_encode_ordered(
1169        &self,
1170        descending: bool,
1171        nulls_last: bool,
1172    ) -> PolarsResult<BinaryOffsetChunked> {
1173        row_encode::_get_rows_encoded_ca(
1174            self.name().clone(),
1175            &[self.clone().into_column()],
1176            &[descending],
1177            &[nulls_last],
1178            false,
1179        )
1180    }
1181}
1182
1183impl Default for Series {
1184    fn default() -> Self {
1185        NullChunked::new(PlSmallStr::EMPTY, 0).into_series()
1186    }
1187}
1188
1189impl Deref for Series {
1190    type Target = dyn SeriesTrait;
1191
1192    #[inline(always)]
1193    fn deref(&self) -> &Self::Target {
1194        self.0.as_ref()
1195    }
1196}
1197
1198impl<'a> AsRef<dyn SeriesTrait + 'a> for Series {
1199    fn as_ref(&self) -> &(dyn SeriesTrait + 'a) {
1200        self.0.as_ref()
1201    }
1202}
1203
1204impl<T: PolarsPhysicalType> AsRef<ChunkedArray<T>> for dyn SeriesTrait + '_ {
1205    fn as_ref(&self) -> &ChunkedArray<T> {
1206        // @NOTE: SeriesTrait `as_any` returns a std::any::Any for the underlying ChunkedArray /
1207        // Logical (so not the SeriesWrap).
1208        let Some(ca) = self.as_any().downcast_ref::<ChunkedArray<T>>() else {
1209            panic!(
1210                "implementation error, cannot get ref {:?} from {:?}",
1211                T::get_static_dtype(),
1212                self.dtype()
1213            );
1214        };
1215
1216        ca
1217    }
1218}
1219
1220impl<T: PolarsPhysicalType> AsMut<ChunkedArray<T>> for dyn SeriesTrait + '_ {
1221    fn as_mut(&mut self) -> &mut ChunkedArray<T> {
1222        if !self.as_any_mut().is::<ChunkedArray<T>>() {
1223            panic!(
1224                "implementation error, cannot get ref {:?} from {:?}",
1225                T::get_static_dtype(),
1226                self.dtype()
1227            );
1228        }
1229
1230        // @NOTE: SeriesTrait `as_any` returns a std::any::Any for the underlying ChunkedArray /
1231        // Logical (so not the SeriesWrap).
1232        self.as_any_mut().downcast_mut::<ChunkedArray<T>>().unwrap()
1233    }
1234}
1235
1236impl BroadcastLength for Series {
1237    fn _broadcast_len(&self) -> usize {
1238        self.len()
1239    }
1240
1241    fn _column_name(&self) -> Option<&str> {
1242        Some(self.name())
1243    }
1244}
1245
1246#[cfg(test)]
1247mod test {
1248    use crate::series::*;
1249
1250    #[test]
1251    fn cast() {
1252        let ar = UInt32Chunked::new("a".into(), &[1, 2]);
1253        let s = ar.into_series();
1254        let s2 = s.cast(&DataType::Int64).unwrap();
1255
1256        assert!(s2.i64().is_ok());
1257        let s2 = s.cast(&DataType::Float32).unwrap();
1258        assert!(s2.f32().is_ok());
1259    }
1260
1261    #[test]
1262    fn new_series() {
1263        let _ = Series::new("boolean series".into(), &vec![true, false, true]);
1264        let _ = Series::new("int series".into(), &[1, 2, 3]);
1265        let ca = Int32Chunked::new("a".into(), &[1, 2, 3]);
1266        let _ = ca.into_series();
1267    }
1268
1269    #[test]
1270    #[cfg(feature = "dtype-date")]
1271    fn roundtrip_list_logical_20311() {
1272        let list = ListChunked::from_chunk_iter(
1273            PlSmallStr::from_static("a"),
1274            [ListArray::new(
1275                ArrowDataType::LargeList(Box::new(ArrowField::new(
1276                    LIST_VALUES_NAME,
1277                    ArrowDataType::Int32,
1278                    true,
1279                ))),
1280                unsafe { polars_arrow::offset::Offsets::new_unchecked(vec![0, 1]) }.into(),
1281                PrimitiveArray::new(ArrowDataType::Int32, vec![1i32].into(), None).to_boxed(),
1282                None,
1283            )],
1284        );
1285        let list = unsafe { list.from_physical_unchecked(DataType::Date) }.unwrap();
1286        assert_eq!(list.dtype(), &DataType::List(Box::new(DataType::Date)));
1287    }
1288
1289    #[test]
1290    #[cfg(feature = "dtype-struct")]
1291    fn new_series_from_empty_structs() {
1292        let dtype = DataType::Struct(vec![]);
1293        let empties = vec![AnyValue::StructOwned(Box::new((vec![], vec![]))); 3];
1294        let s = Series::from_any_values_and_dtype("".into(), &empties, &dtype, false).unwrap();
1295        assert_eq!(s.len(), 3);
1296    }
1297    #[test]
1298    fn new_series_from_arrow_primitive_array() {
1299        let array = UInt32Array::from_slice([1, 2, 3, 4, 5]);
1300        let array_ref: ArrayRef = Box::new(array);
1301
1302        let _ = Series::try_new("foo".into(), array_ref).unwrap();
1303    }
1304
1305    #[test]
1306    fn series_append() {
1307        let mut s1 = Series::new("a".into(), &[1, 2]);
1308        let s2 = Series::new("b".into(), &[3]);
1309        s1.append(&s2).unwrap();
1310        assert_eq!(s1.len(), 3);
1311
1312        // add wrong type
1313        let s2 = Series::new("b".into(), &[3.0]);
1314        assert!(s1.append(&s2).is_err())
1315    }
1316
1317    #[test]
1318    #[cfg(feature = "dtype-decimal")]
1319    fn series_append_decimal() {
1320        let s1 = Series::new("a".into(), &[1.1, 2.3])
1321            .cast(&DataType::Decimal(38, 2))
1322            .unwrap();
1323        let s2 = Series::new("b".into(), &[3])
1324            .cast(&DataType::Decimal(38, 0))
1325            .unwrap();
1326
1327        {
1328            let mut s1 = s1.clone();
1329            s1.append(&s2).unwrap();
1330            assert_eq!(s1.len(), 3);
1331            assert_eq!(s1.get(2).unwrap(), AnyValue::Decimal(300, 38, 2));
1332        }
1333
1334        {
1335            let mut s2 = s2;
1336            s2.extend(&s1).unwrap();
1337            assert_eq!(s2.get(2).unwrap(), AnyValue::Decimal(2, 38, 0));
1338        }
1339    }
1340
1341    #[test]
1342    fn series_slice_works() {
1343        let series = Series::new("a".into(), &[1i64, 2, 3, 4, 5]);
1344
1345        let slice_1 = series.slice((-3i64, 3));
1346        let slice_2 = series.slice((-5i64, 5));
1347        let slice_3 = series.slice(Slice::head(5));
1348
1349        assert_eq!(slice_1.get(0).unwrap(), AnyValue::Int64(3));
1350        assert_eq!(slice_2.get(0).unwrap(), AnyValue::Int64(1));
1351        assert_eq!(slice_3.get(0).unwrap(), AnyValue::Int64(1));
1352    }
1353
1354    #[test]
1355    fn out_of_range_slice_does_not_panic() {
1356        let series = Series::new("a".into(), &[1i64, 2, 3, 4, 5]);
1357
1358        let _ = series.slice((-3i64, 4));
1359        let _ = series.slice((-6i64, 2));
1360        let _ = series.slice((4usize, 2));
1361    }
1362}