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