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
37use arrow::compute::aggregate::estimated_bytes_size;
38use arrow::offset::Offsets;
39pub use from::*;
40pub use iterator::{SeriesIter, SeriesPhysIter};
41use num_traits::NumCast;
42use polars_error::feature_gated;
43use polars_utils::float::IsFloat;
44pub use series_trait::{IsSorted, *};
45
46use crate::chunked_array::cast::CastOptions;
47use crate::runtime::RAYON;
48#[cfg(feature = "zip_with")]
49use crate::series::arithmetic::coerce_lhs_rhs;
50use crate::utils::{Wrap, handle_casting_failures, materialize_dyn_int};
51
52/// # Series
53/// The columnar data type for a DataFrame.
54///
55/// Most of the available functions are defined in the [SeriesTrait trait](crate::series::SeriesTrait).
56///
57/// The `Series` struct consists
58/// of typed [ChunkedArray]'s. To quickly cast
59/// a `Series` to a `ChunkedArray` you can call the method with the name of the type:
60///
61/// ```
62/// # use polars_core::prelude::*;
63/// let s: Series = [1, 2, 3].iter().collect();
64/// // Quickly obtain the ChunkedArray wrapped by the Series.
65/// let chunked_array = s.i32().unwrap();
66/// ```
67///
68/// ## Arithmetic
69///
70/// You can do standard arithmetic on series.
71/// ```
72/// # use polars_core::prelude::*;
73/// let s = Series::new("a".into(), [1 , 2, 3]);
74/// let out_add = &s + &s;
75/// let out_sub = &s - &s;
76/// let out_div = &s / &s;
77/// let out_mul = &s * &s;
78/// ```
79///
80/// Or with series and numbers.
81///
82/// ```
83/// # use polars_core::prelude::*;
84/// let s: Series = (1..3).collect();
85/// let out_add_one = &s + 1;
86/// let out_multiply = &s * 10;
87///
88/// // Could not overload left hand side operator.
89/// let out_divide = 1.div(&s);
90/// let out_add = 1.add(&s);
91/// let out_subtract = 1.sub(&s);
92/// let out_multiply = 1.mul(&s);
93/// ```
94///
95/// ## Comparison
96/// You can obtain boolean mask by comparing series.
97///
98/// ```
99/// # use polars_core::prelude::*;
100/// let s = Series::new("dollars".into(), &[1, 2, 3]);
101/// let mask = s.equal(1).unwrap();
102/// let valid = [true, false, false].iter();
103/// assert!(mask
104///     .iter()
105///     .map(|opt_bool| opt_bool.unwrap()) // option, because series can be null
106///     .zip(valid)
107///     .all(|(a, b)| a == *b))
108/// ```
109///
110/// See all the comparison operators in the [ChunkCompareEq trait](crate::chunked_array::ops::ChunkCompareEq) and
111/// [ChunkCompareIneq trait](crate::chunked_array::ops::ChunkCompareIneq).
112///
113/// ## Iterators
114/// The Series variants contain differently typed [ChunkedArray]s.
115/// These structs can be turned into iterators, making it possible to use any function/ closure you want
116/// on a Series.
117///
118/// These iterators return an `Option<T>` because the values of a series may be null.
119///
120/// ```
121/// use polars_core::prelude::*;
122/// let pi = 3.14;
123/// let s = Series::new("angle".into(), [2f32 * pi, pi, 1.5 * pi].as_ref());
124/// let s_cos: Series = s.f32()
125///                     .expect("series was not an f32 dtype")
126///                     .iter()
127///                     .map(|opt_angle| opt_angle.map(|angle| angle.cos()))
128///                     .collect();
129/// ```
130///
131/// ## Creation
132/// Series can be create from different data structures. Below we'll show a few ways we can create
133/// a Series object.
134///
135/// ```
136/// # use polars_core::prelude::*;
137/// // Series can be created from Vec's, slices and arrays
138/// Series::new("boolean series".into(), &[true, false, true]);
139/// Series::new("int series".into(), &[1, 2, 3]);
140/// // And can be nullable
141/// Series::new("got nulls".into(), &[Some(1), None, Some(2)]);
142///
143/// // Series can also be collected from iterators
144/// let from_iter: Series = (0..10)
145///     .into_iter()
146///     .collect();
147///
148/// ```
149#[derive(Clone)]
150#[must_use]
151pub struct Series(pub Arc<dyn SeriesTrait>);
152
153impl PartialEq for Wrap<Series> {
154    fn eq(&self, other: &Self) -> bool {
155        self.0.equals_missing(other)
156    }
157}
158
159impl Eq for Wrap<Series> {}
160
161impl Hash for Wrap<Series> {
162    fn hash<H: Hasher>(&self, state: &mut H) {
163        self.dtype().hash(state);
164        self.len().hash(state);
165
166        for av in self.iter() {
167            av.hash(state);
168        }
169    }
170}
171
172impl Series {
173    /// Create a new empty Series.
174    pub fn new_empty(name: PlSmallStr, dtype: &DataType) -> Series {
175        Series::full_null(name, 0, dtype)
176    }
177
178    pub fn clear(&self) -> Series {
179        if self.is_empty() {
180            self.clone()
181        } else {
182            match self.dtype() {
183                #[cfg(feature = "object")]
184                DataType::Object(_) => self
185                    .take(&ChunkedArray::<IdxType>::new_vec(PlSmallStr::EMPTY, vec![]))
186                    .unwrap(),
187                dt => Series::new_empty(self.name().clone(), dt),
188            }
189        }
190    }
191
192    #[doc(hidden)]
193    pub fn _get_inner_mut(&mut self) -> &mut dyn SeriesTrait {
194        if Arc::weak_count(&self.0) + Arc::strong_count(&self.0) != 1 {
195            self.0 = self.0.clone_inner();
196        }
197        Arc::get_mut(&mut self.0).expect("implementation error")
198    }
199
200    /// Take or clone a owned copy of the inner [`ChunkedArray`].
201    pub fn take_inner<T: PolarsPhysicalType>(self) -> ChunkedArray<T> {
202        let arc_any = self.0.as_arc_any();
203        let downcast = arc_any
204            .downcast::<implementations::SeriesWrap<ChunkedArray<T>>>()
205            .unwrap();
206
207        match Arc::try_unwrap(downcast) {
208            Ok(ca) => ca.0,
209            Err(ca) => ca.as_ref().as_ref().clone(),
210        }
211    }
212
213    /// Returns a reference to the Arrow ArrayRef
214    #[inline]
215    pub fn array_ref(&self, chunk_idx: usize) -> &ArrayRef {
216        &self.chunks()[chunk_idx] as &ArrayRef
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_unchecked(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.is_extension()) && 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, if not nested.
467            // Nested types could hide cast errors, so have to be done internally.
468            CastOptions::Strict if !dtype.is_nested() => CastOptions::NonStrict,
469            opt => opt,
470        };
471
472        let out = slf.0.cast(dtype, new_options)?;
473        if options.is_strict() {
474            handle_casting_failures(slf.as_ref(), &out)?;
475        }
476        Ok(out)
477    }
478
479    /// Cast from physical to logical types without any checks on the validity of the cast.
480    ///
481    /// # Safety
482    ///
483    /// This can lead to invalid memory access in downstream code.
484    pub unsafe fn cast_unchecked(&self, dtype: &DataType) -> PolarsResult<Self> {
485        match self.dtype() {
486            #[cfg(feature = "dtype-struct")]
487            DataType::Struct(_) => self.struct_().unwrap().cast_unchecked(dtype),
488            DataType::List(_) => self.list().unwrap().cast_unchecked(dtype),
489            dt if dt.is_primitive_numeric() => {
490                with_match_physical_numeric_polars_type!(dt, |$T| {
491                    let ca: &ChunkedArray<$T> = self.as_ref().as_ref().as_ref();
492                        ca.cast_unchecked(dtype)
493                })
494            },
495            DataType::Binary => self.binary().unwrap().cast_unchecked(dtype),
496            _ => self.cast_with_options(dtype, CastOptions::Overflowing),
497        }
498    }
499
500    /// Convert a non-logical series back into a logical series without casting.
501    ///
502    /// # Safety
503    ///
504    /// This can lead to invalid memory access in downstream code.
505    pub unsafe fn from_physical_unchecked(&self, dtype: &DataType) -> PolarsResult<Self> {
506        debug_assert!(!self.dtype().is_logical(), "{:?}", self.dtype());
507
508        if self.dtype() == dtype {
509            return Ok(self.clone());
510        }
511
512        use DataType as D;
513        match (self.dtype(), dtype) {
514            #[cfg(feature = "dtype-decimal")]
515            (D::Int128, D::Decimal(precision, scale)) => {
516                let ca = self.i128().unwrap();
517                Ok(ca
518                    .clone()
519                    .into_decimal_unchecked(*precision, *scale)
520                    .into_series())
521            },
522
523            #[cfg(feature = "dtype-categorical")]
524            (phys, D::Categorical(cats, _)) if &cats.physical().dtype() == phys => {
525                with_match_categorical_physical_type!(cats.physical(), |$C| {
526                    type CA = ChunkedArray<<$C as PolarsCategoricalType>::PolarsPhysical>;
527                    let ca = self.as_ref().as_any().downcast_ref::<CA>().unwrap();
528                    Ok(CategoricalChunked::<$C>::from_cats_and_dtype_unchecked(
529                        ca.clone(),
530                        dtype.clone(),
531                    )
532                    .into_series())
533                })
534            },
535            #[cfg(feature = "dtype-categorical")]
536            (phys, D::Enum(fcats, _)) if &fcats.physical().dtype() == phys => {
537                with_match_categorical_physical_type!(fcats.physical(), |$C| {
538                    type CA = ChunkedArray<<$C as PolarsCategoricalType>::PolarsPhysical>;
539                    let ca = self.as_ref().as_any().downcast_ref::<CA>().unwrap();
540                    Ok(CategoricalChunked::<$C>::from_cats_and_dtype_unchecked(
541                        ca.clone(),
542                        dtype.clone(),
543                    )
544                    .into_series())
545                })
546            },
547
548            (D::Int32, D::Date) => feature_gated!("dtype-time", Ok(self.clone().into_date())),
549            (D::Int64, D::Datetime(tu, tz)) => feature_gated!(
550                "dtype-datetime",
551                Ok(self.clone().into_datetime(*tu, tz.clone()))
552            ),
553            (D::Int64, D::Duration(tu)) => {
554                feature_gated!("dtype-duration", Ok(self.clone().into_duration(*tu)))
555            },
556            (D::Int64, D::Time) => feature_gated!("dtype-time", Ok(self.clone().into_time())),
557
558            (D::List(_), D::List(to)) => unsafe {
559                self.list()
560                    .unwrap()
561                    .from_physical_unchecked(to.as_ref().clone())
562                    .map(|ca| ca.into_series())
563            },
564            #[cfg(feature = "dtype-array")]
565            (D::Array(_, lw), D::Array(to, rw)) if lw == rw => unsafe {
566                self.array()
567                    .unwrap()
568                    .from_physical_unchecked(to.as_ref().clone())
569                    .map(|ca| ca.into_series())
570            },
571            #[cfg(feature = "dtype-struct")]
572            (D::Struct(_), D::Struct(to)) => unsafe {
573                self.struct_()
574                    .unwrap()
575                    .from_physical_unchecked(to.as_slice())
576                    .map(|ca| ca.into_series())
577            },
578
579            #[cfg(feature = "dtype-extension")]
580            (_, D::Extension(typ, storage)) => {
581                let storage_series = self.from_physical_unchecked(storage.as_ref())?;
582                let ext = ExtensionChunked::from_storage(typ.clone(), storage_series);
583                Ok(ext.into_series())
584            },
585
586            _ => panic!("invalid from_physical({dtype:?}) for {:?}", self.dtype()),
587        }
588    }
589
590    #[cfg(feature = "dtype-extension")]
591    pub fn into_extension(self, typ: ExtensionTypeInstance) -> Series {
592        assert!(!self.dtype().is_extension());
593        let ext = ExtensionChunked::from_storage(typ, self);
594        ext.into_series()
595    }
596
597    /// Cast numerical types to f64, and keep floats as is.
598    pub fn to_float(&self) -> PolarsResult<Series> {
599        match self.dtype() {
600            DataType::Float32 | DataType::Float64 => Ok(self.clone()),
601            _ => self.cast_with_options(&DataType::Float64, CastOptions::Overflowing),
602        }
603    }
604
605    /// Compute the sum of all values in this Series.
606    /// Returns `Some(0)` if the array is empty, and `None` if the array only
607    /// contains null values.
608    ///
609    /// If the [`DataType`] is one of `{Int8, UInt8, Int16, UInt16}` the `Series` is
610    /// first cast to `Int64` to prevent overflow issues.
611    pub fn sum<T>(&self) -> PolarsResult<T>
612    where
613        T: NumCast + IsFloat,
614    {
615        let sum = self.sum_reduce()?;
616        let sum = sum.value().extract().unwrap();
617        Ok(sum)
618    }
619
620    /// Returns the minimum value in the array, according to the natural order.
621    /// Returns an option because the array is nullable.
622    pub fn min<T>(&self) -> PolarsResult<Option<T>>
623    where
624        T: NumCast + IsFloat,
625    {
626        let min = self.min_reduce()?;
627        let min = min.value().extract::<T>();
628        Ok(min)
629    }
630
631    /// Returns the maximum value in the array, according to the natural order.
632    /// Returns an option because the array is nullable.
633    pub fn max<T>(&self) -> PolarsResult<Option<T>>
634    where
635        T: NumCast + IsFloat,
636    {
637        let max = self.max_reduce()?;
638        let max = max.value().extract::<T>();
639        Ok(max)
640    }
641
642    /// Explode a list Series. This expands every item to a new row..
643    pub fn explode(&self, options: ExplodeOptions) -> PolarsResult<Series> {
644        match self.dtype() {
645            DataType::List(_) => self.list().unwrap().explode(options),
646            #[cfg(feature = "dtype-array")]
647            DataType::Array(_, _) => self.array().unwrap().explode(options),
648            _ => Ok(self.clone()),
649        }
650    }
651
652    /// Check if numeric value is NaN (note this is different than missing/ null)
653    pub fn is_nan(&self) -> PolarsResult<BooleanChunked> {
654        match self.dtype() {
655            #[cfg(feature = "dtype-f16")]
656            DataType::Float16 => Ok(self.f16().unwrap().is_nan()),
657            DataType::Float32 => Ok(self.f32().unwrap().is_nan()),
658            DataType::Float64 => Ok(self.f64().unwrap().is_nan()),
659            DataType::Null => Ok(BooleanChunked::full_null(self.name().clone(), self.len())),
660            dt if dt.is_primitive_numeric() => {
661                let arr = BooleanArray::full(self.len(), false, ArrowDataType::Boolean)
662                    .with_validity(self.rechunk_validity());
663                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
664            },
665            _ => polars_bail!(opq = is_nan, self.dtype()),
666        }
667    }
668
669    /// Check if numeric value is NaN (note this is different than missing/null)
670    pub fn is_not_nan(&self) -> PolarsResult<BooleanChunked> {
671        match self.dtype() {
672            #[cfg(feature = "dtype-f16")]
673            DataType::Float16 => Ok(self.f16().unwrap().is_not_nan()),
674            DataType::Float32 => Ok(self.f32().unwrap().is_not_nan()),
675            DataType::Float64 => Ok(self.f64().unwrap().is_not_nan()),
676            dt if dt.is_primitive_numeric() => {
677                let arr = BooleanArray::full(self.len(), true, ArrowDataType::Boolean)
678                    .with_validity(self.rechunk_validity());
679                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
680            },
681            _ => polars_bail!(opq = is_not_nan, self.dtype()),
682        }
683    }
684
685    /// Check if numeric value is finite
686    pub fn is_finite(&self) -> PolarsResult<BooleanChunked> {
687        match self.dtype() {
688            #[cfg(feature = "dtype-f16")]
689            DataType::Float16 => Ok(self.f16().unwrap().is_finite()),
690            DataType::Float32 => Ok(self.f32().unwrap().is_finite()),
691            DataType::Float64 => Ok(self.f64().unwrap().is_finite()),
692            DataType::Null => Ok(BooleanChunked::full_null(self.name().clone(), self.len())),
693            dt if dt.is_primitive_numeric() => {
694                let arr = BooleanArray::full(self.len(), true, ArrowDataType::Boolean)
695                    .with_validity(self.rechunk_validity());
696                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
697            },
698            _ => polars_bail!(opq = is_finite, self.dtype()),
699        }
700    }
701
702    /// Check if numeric value is infinite
703    pub fn is_infinite(&self) -> PolarsResult<BooleanChunked> {
704        match self.dtype() {
705            #[cfg(feature = "dtype-f16")]
706            DataType::Float16 => Ok(self.f16().unwrap().is_infinite()),
707            DataType::Float32 => Ok(self.f32().unwrap().is_infinite()),
708            DataType::Float64 => Ok(self.f64().unwrap().is_infinite()),
709            DataType::Null => Ok(BooleanChunked::full_null(self.name().clone(), self.len())),
710            dt if dt.is_primitive_numeric() => {
711                let arr = BooleanArray::full(self.len(), false, ArrowDataType::Boolean)
712                    .with_validity(self.rechunk_validity());
713                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
714            },
715            _ => polars_bail!(opq = is_infinite, self.dtype()),
716        }
717    }
718
719    /// Create a new ChunkedArray with values from self where the mask evaluates `true` and values
720    /// from `other` where the mask evaluates `false`. This function automatically broadcasts unit
721    /// length inputs.
722    #[cfg(feature = "zip_with")]
723    pub fn zip_with(&self, mask: &BooleanChunked, other: &Series) -> PolarsResult<Series> {
724        let (lhs, rhs) = coerce_lhs_rhs(self, other)?;
725        lhs.zip_with_same_type(mask, rhs.as_ref())
726    }
727
728    /// Converts a Series to their physical representation, if they have one,
729    /// otherwise the series is left unchanged.
730    ///
731    /// * Date -> Int32
732    /// * Datetime -> Int64
733    /// * Duration -> Int64
734    /// * Decimal -> Int128
735    /// * Time -> Int64
736    /// * Categorical -> U8/U16/U32
737    /// * List(inner) -> List(physical of inner)
738    /// * Array(inner) -> Array(physical of inner)
739    /// * Struct -> Struct with physical repr of each struct column
740    /// * Extension -> physical of storage type
741    pub fn to_physical_repr(&self) -> Cow<'_, Series> {
742        use DataType::*;
743        match self.dtype() {
744            // NOTE: Don't use cast here, as it might rechunk (if all nulls)
745            // which is not allowed in a phys repr.
746            #[cfg(feature = "dtype-date")]
747            Date => Cow::Owned(self.date().unwrap().phys.clone().into_series()),
748            #[cfg(feature = "dtype-datetime")]
749            Datetime(_, _) => Cow::Owned(self.datetime().unwrap().phys.clone().into_series()),
750            #[cfg(feature = "dtype-duration")]
751            Duration(_) => Cow::Owned(self.duration().unwrap().phys.clone().into_series()),
752            #[cfg(feature = "dtype-time")]
753            Time => Cow::Owned(self.time().unwrap().phys.clone().into_series()),
754            #[cfg(feature = "dtype-categorical")]
755            dt @ (Categorical(_, _) | Enum(_, _)) => {
756                with_match_categorical_physical_type!(dt.cat_physical().unwrap(), |$C| {
757                    let ca = self.cat::<$C>().unwrap();
758                    Cow::Owned(ca.physical().clone().into_series())
759                })
760            },
761            #[cfg(feature = "dtype-decimal")]
762            Decimal(_, _) => Cow::Owned(self.decimal().unwrap().phys.clone().into_series()),
763            List(_) => match self.list().unwrap().to_physical_repr() {
764                Cow::Borrowed(_) => Cow::Borrowed(self),
765                Cow::Owned(ca) => Cow::Owned(ca.into_series()),
766            },
767            #[cfg(feature = "dtype-array")]
768            Array(_, _) => match self.array().unwrap().to_physical_repr() {
769                Cow::Borrowed(_) => Cow::Borrowed(self),
770                Cow::Owned(ca) => Cow::Owned(ca.into_series()),
771            },
772            #[cfg(feature = "dtype-struct")]
773            Struct(_) => match self.struct_().unwrap().to_physical_repr() {
774                Cow::Borrowed(_) => Cow::Borrowed(self),
775                Cow::Owned(ca) => Cow::Owned(ca.into_series()),
776            },
777            #[cfg(feature = "dtype-extension")]
778            Extension(_, _) => self.ext().unwrap().storage().to_physical_repr(),
779            _ => Cow::Borrowed(self),
780        }
781    }
782
783    /// If the Series is an Extension type, return its storage Series.
784    /// Otherwise, return itself.
785    pub fn to_storage(&self) -> &Series {
786        #[cfg(feature = "dtype-extension")]
787        {
788            if let DataType::Extension(_, _) = self.dtype() {
789                return self.ext().unwrap().storage();
790            }
791        }
792        self
793    }
794
795    /// Traverse and collect every nth element in a new array.
796    pub fn gather_every(&self, n: usize, offset: usize) -> PolarsResult<Series> {
797        polars_ensure!(n > 0, ComputeError: "cannot perform gather every for `n=0`");
798        let idx = ((offset as IdxSize)..self.len() as IdxSize)
799            .step_by(n)
800            .collect_ca(PlSmallStr::EMPTY);
801        // SAFETY: we stay in-bounds.
802        Ok(unsafe { self.take_unchecked(&idx) })
803    }
804
805    #[cfg(feature = "dot_product")]
806    pub fn dot(&self, other: &Series) -> PolarsResult<f64> {
807        std::ops::Mul::mul(self, other)?.sum::<f64>()
808    }
809
810    /// Get the sum of the Series as a new Series of length 1.
811    /// Returns a Series with a single zeroed entry if self is an empty numeric series.
812    ///
813    /// If the [`DataType`] is one of `{Int8, UInt8, Int16, UInt16}` the `Series` is
814    /// first cast to `Int64` to prevent overflow issues.
815    pub fn sum_reduce(&self) -> PolarsResult<Scalar> {
816        use DataType::*;
817        match self.dtype() {
818            Int8 | UInt8 | Int16 | UInt16 => self.cast(&Int64).unwrap().sum_reduce(),
819            _ => self.0.sum_reduce(),
820        }
821    }
822
823    /// Get the mean of the Series as a new Series of length 1.
824    /// Returns a Series with a single null entry if self is an empty numeric series.
825    pub fn mean_reduce(&self) -> PolarsResult<Scalar> {
826        self.0.mean_reduce()
827    }
828
829    /// Get the product of an array.
830    ///
831    /// If the [`DataType`] is one of `{Int8, UInt8, Int16, UInt16}` the `Series` is
832    /// first cast to `Int64` to prevent overflow issues.
833    pub fn product(&self) -> PolarsResult<Scalar> {
834        #[cfg(feature = "product")]
835        {
836            use DataType::*;
837            match self.dtype() {
838                Boolean => self.cast(&DataType::Int64).unwrap().product(),
839                Int8 | UInt8 | Int16 | UInt16 | Int32 | UInt32 => {
840                    let s = self.cast(&Int64).unwrap();
841                    s.product()
842                },
843                Int64 => Ok(self.i64().unwrap().prod_reduce()),
844                UInt64 => Ok(self.u64().unwrap().prod_reduce()),
845                #[cfg(feature = "dtype-i128")]
846                Int128 => Ok(self.i128().unwrap().prod_reduce()),
847                #[cfg(feature = "dtype-u128")]
848                UInt128 => Ok(self.u128().unwrap().prod_reduce()),
849                #[cfg(feature = "dtype-f16")]
850                Float16 => Ok(self.f16().unwrap().prod_reduce()),
851                Float32 => Ok(self.f32().unwrap().prod_reduce()),
852                Float64 => Ok(self.f64().unwrap().prod_reduce()),
853                #[cfg(feature = "dtype-decimal")]
854                Decimal(..) => Ok(self.decimal().unwrap().prod_reduce()),
855                dt => {
856                    polars_bail!(InvalidOperation: "`product` operation not supported for dtype `{dt}`")
857                },
858            }
859        }
860        #[cfg(not(feature = "product"))]
861        {
862            panic!("activate 'product' feature")
863        }
864    }
865
866    /// Cast throws an error if conversion had overflows
867    pub fn strict_cast(&self, dtype: &DataType) -> PolarsResult<Series> {
868        self.cast_with_options(dtype, CastOptions::Strict)
869    }
870
871    #[cfg(feature = "dtype-decimal")]
872    pub fn into_decimal(self, precision: usize, scale: usize) -> PolarsResult<Series> {
873        match self.dtype() {
874            DataType::Int128 => Ok(self
875                .i128()
876                .unwrap()
877                .clone()
878                .into_decimal(precision, scale)?
879                .into_series()),
880            DataType::Decimal(cur_prec, cur_scale)
881                if scale == *cur_scale && precision >= *cur_prec =>
882            {
883                Ok(self)
884            },
885            dt => panic!("into_decimal({precision:?}, {scale}) not implemented for {dt:?}"),
886        }
887    }
888
889    #[cfg(feature = "dtype-time")]
890    pub fn into_time(self) -> Series {
891        match self.dtype() {
892            DataType::Int64 => self.i64().unwrap().clone().into_time().into_series(),
893            DataType::Time => self
894                .time()
895                .unwrap()
896                .physical()
897                .clone()
898                .into_time()
899                .into_series(),
900            dt => panic!("date not implemented for {dt:?}"),
901        }
902    }
903
904    pub fn into_date(self) -> Series {
905        #[cfg(not(feature = "dtype-date"))]
906        {
907            panic!("activate feature dtype-date")
908        }
909        #[cfg(feature = "dtype-date")]
910        match self.dtype() {
911            DataType::Int32 => self.i32().unwrap().clone().into_date().into_series(),
912            DataType::Date => self
913                .date()
914                .unwrap()
915                .physical()
916                .clone()
917                .into_date()
918                .into_series(),
919            dt => panic!("date not implemented for {dt:?}"),
920        }
921    }
922
923    #[allow(unused_variables)]
924    pub fn into_datetime(self, timeunit: TimeUnit, tz: Option<TimeZone>) -> Series {
925        #[cfg(not(feature = "dtype-datetime"))]
926        {
927            panic!("activate feature dtype-datetime")
928        }
929
930        #[cfg(feature = "dtype-datetime")]
931        match self.dtype() {
932            DataType::Int64 => self
933                .i64()
934                .unwrap()
935                .clone()
936                .into_datetime(timeunit, tz)
937                .into_series(),
938            DataType::Datetime(_, _) => self
939                .datetime()
940                .unwrap()
941                .physical()
942                .clone()
943                .into_datetime(timeunit, tz)
944                .into_series(),
945            dt => panic!("into_datetime not implemented for {dt:?}"),
946        }
947    }
948
949    #[allow(unused_variables)]
950    pub fn into_duration(self, timeunit: TimeUnit) -> Series {
951        #[cfg(not(feature = "dtype-duration"))]
952        {
953            panic!("activate feature dtype-duration")
954        }
955        #[cfg(feature = "dtype-duration")]
956        match self.dtype() {
957            DataType::Int64 => self
958                .i64()
959                .unwrap()
960                .clone()
961                .into_duration(timeunit)
962                .into_series(),
963            DataType::Duration(_) => self
964                .duration()
965                .unwrap()
966                .physical()
967                .clone()
968                .into_duration(timeunit)
969                .into_series(),
970            dt => panic!("into_duration not implemented for {dt:?}"),
971        }
972    }
973
974    // used for formatting
975    pub fn str_value(&self, index: usize) -> PolarsResult<Cow<'_, str>> {
976        Ok(self.0.get(index)?.str_value())
977    }
978    /// Get the head of the Series.
979    pub fn head(&self, length: Option<usize>) -> Series {
980        let len = length.unwrap_or(HEAD_DEFAULT_LENGTH);
981        self.slice(0, std::cmp::min(len, self.len()))
982    }
983
984    /// Get the tail of the Series.
985    pub fn tail(&self, length: Option<usize>) -> Series {
986        let len = length.unwrap_or(TAIL_DEFAULT_LENGTH);
987        let len = std::cmp::min(len, self.len());
988        self.slice(-(len as i64), len)
989    }
990
991    /// Compute the unique elements, but maintain order. This requires more work
992    /// than a naive [`Series::unique`](SeriesTrait::unique).
993    pub fn unique_stable(&self) -> PolarsResult<Series> {
994        let idx = self.arg_unique()?;
995        // SAFETY: Indices are in bounds.
996        unsafe { Ok(self.take_unchecked(&idx)) }
997    }
998
999    pub fn try_idx(&self) -> Option<&IdxCa> {
1000        #[cfg(feature = "bigidx")]
1001        {
1002            self.try_u64()
1003        }
1004        #[cfg(not(feature = "bigidx"))]
1005        {
1006            self.try_u32()
1007        }
1008    }
1009
1010    pub fn idx(&self) -> PolarsResult<&IdxCa> {
1011        #[cfg(feature = "bigidx")]
1012        {
1013            self.u64()
1014        }
1015        #[cfg(not(feature = "bigidx"))]
1016        {
1017            self.u32()
1018        }
1019    }
1020
1021    /// Returns an estimation of the total (heap) allocated size of the `Series` in bytes.
1022    ///
1023    /// # Implementation
1024    /// This estimation is the sum of the size of its buffers, validity, including nested arrays.
1025    /// Multiple arrays may share buffers and bitmaps. Therefore, the size of 2 arrays is not the
1026    /// sum of the sizes computed from this function. In particular, [`StructArray`]'s size is an upper bound.
1027    ///
1028    /// When an array is sliced, its allocated size remains constant because the buffer unchanged.
1029    /// However, this function will yield a smaller number. This is because this function returns
1030    /// the visible size of the buffer, not its total capacity.
1031    ///
1032    /// FFI buffers are included in this estimation.
1033    pub fn estimated_size(&self) -> usize {
1034        let mut size = 0;
1035        match self.dtype() {
1036            // TODO @ cat-rework: include mapping size here?
1037            #[cfg(feature = "object")]
1038            DataType::Object(_) => {
1039                let ArrowDataType::FixedSizeBinary(size) = self.chunks()[0].dtype() else {
1040                    unreachable!()
1041                };
1042                // This is only the pointer size in python. So will be a huge underestimation.
1043                return self.len() * *size;
1044            },
1045            _ => {},
1046        }
1047
1048        size += self
1049            .chunks()
1050            .iter()
1051            .map(|arr| estimated_bytes_size(&**arr))
1052            .sum::<usize>();
1053
1054        size
1055    }
1056
1057    /// Packs every element into a list.
1058    pub fn as_list(&self) -> ListChunked {
1059        let s = self.rechunk();
1060        // don't  use `to_arrow` as we need the physical types
1061        let values = s.chunks()[0].clone();
1062        let offsets = (0i64..(s.len() as i64 + 1)).collect::<Vec<_>>();
1063        let offsets = unsafe { Offsets::new_unchecked(offsets) };
1064
1065        let dtype = LargeListArray::default_datatype(
1066            s.dtype().to_physical().to_arrow(CompatLevel::newest()),
1067        );
1068        let new_arr = LargeListArray::new(dtype, offsets.into(), values, None);
1069        let mut out = ListChunked::with_chunk(s.name().clone(), new_arr);
1070        out.set_inner_dtype(s.dtype().clone());
1071        out
1072    }
1073
1074    pub fn row_encode_unordered(&self) -> PolarsResult<BinaryOffsetChunked> {
1075        row_encode::_get_rows_encoded_ca_unordered(
1076            self.name().clone(),
1077            &[self.clone().into_column()],
1078        )
1079    }
1080
1081    pub fn row_encode_ordered(
1082        &self,
1083        descending: bool,
1084        nulls_last: bool,
1085    ) -> PolarsResult<BinaryOffsetChunked> {
1086        row_encode::_get_rows_encoded_ca(
1087            self.name().clone(),
1088            &[self.clone().into_column()],
1089            &[descending],
1090            &[nulls_last],
1091            false,
1092        )
1093    }
1094}
1095
1096impl Default for Series {
1097    fn default() -> Self {
1098        NullChunked::new(PlSmallStr::EMPTY, 0).into_series()
1099    }
1100}
1101
1102impl Deref for Series {
1103    type Target = dyn SeriesTrait;
1104
1105    fn deref(&self) -> &Self::Target {
1106        self.0.as_ref()
1107    }
1108}
1109
1110impl<'a> AsRef<dyn SeriesTrait + 'a> for Series {
1111    fn as_ref(&self) -> &(dyn SeriesTrait + 'a) {
1112        self.0.as_ref()
1113    }
1114}
1115
1116impl<T: PolarsPhysicalType> AsRef<ChunkedArray<T>> for dyn SeriesTrait + '_ {
1117    fn as_ref(&self) -> &ChunkedArray<T> {
1118        // @NOTE: SeriesTrait `as_any` returns a std::any::Any for the underlying ChunkedArray /
1119        // Logical (so not the SeriesWrap).
1120        let Some(ca) = self.as_any().downcast_ref::<ChunkedArray<T>>() else {
1121            panic!(
1122                "implementation error, cannot get ref {:?} from {:?}",
1123                T::get_static_dtype(),
1124                self.dtype()
1125            );
1126        };
1127
1128        ca
1129    }
1130}
1131
1132impl<T: PolarsPhysicalType> AsMut<ChunkedArray<T>> for dyn SeriesTrait + '_ {
1133    fn as_mut(&mut self) -> &mut ChunkedArray<T> {
1134        if !self.as_any_mut().is::<ChunkedArray<T>>() {
1135            panic!(
1136                "implementation error, cannot get ref {:?} from {:?}",
1137                T::get_static_dtype(),
1138                self.dtype()
1139            );
1140        }
1141
1142        // @NOTE: SeriesTrait `as_any` returns a std::any::Any for the underlying ChunkedArray /
1143        // Logical (so not the SeriesWrap).
1144        self.as_any_mut().downcast_mut::<ChunkedArray<T>>().unwrap()
1145    }
1146}
1147
1148#[cfg(test)]
1149mod test {
1150    use crate::prelude::*;
1151    use crate::series::*;
1152
1153    #[test]
1154    fn cast() {
1155        let ar = UInt32Chunked::new("a".into(), &[1, 2]);
1156        let s = ar.into_series();
1157        let s2 = s.cast(&DataType::Int64).unwrap();
1158
1159        assert!(s2.i64().is_ok());
1160        let s2 = s.cast(&DataType::Float32).unwrap();
1161        assert!(s2.f32().is_ok());
1162    }
1163
1164    #[test]
1165    fn new_series() {
1166        let _ = Series::new("boolean series".into(), &vec![true, false, true]);
1167        let _ = Series::new("int series".into(), &[1, 2, 3]);
1168        let ca = Int32Chunked::new("a".into(), &[1, 2, 3]);
1169        let _ = ca.into_series();
1170    }
1171
1172    #[test]
1173    #[cfg(feature = "dtype-date")]
1174    fn roundtrip_list_logical_20311() {
1175        let list = ListChunked::from_chunk_iter(
1176            PlSmallStr::from_static("a"),
1177            [ListArray::new(
1178                ArrowDataType::LargeList(Box::new(ArrowField::new(
1179                    LIST_VALUES_NAME,
1180                    ArrowDataType::Int32,
1181                    true,
1182                ))),
1183                unsafe { Offsets::new_unchecked(vec![0, 1]) }.into(),
1184                PrimitiveArray::new(ArrowDataType::Int32, vec![1i32].into(), None).to_boxed(),
1185                None,
1186            )],
1187        );
1188        let list = unsafe { list.from_physical_unchecked(DataType::Date) }.unwrap();
1189        assert_eq!(list.dtype(), &DataType::List(Box::new(DataType::Date)));
1190    }
1191
1192    #[test]
1193    #[cfg(feature = "dtype-struct")]
1194    fn new_series_from_empty_structs() {
1195        let dtype = DataType::Struct(vec![]);
1196        let empties = vec![AnyValue::StructOwned(Box::new((vec![], vec![]))); 3];
1197        let s = Series::from_any_values_and_dtype("".into(), &empties, &dtype, false).unwrap();
1198        assert_eq!(s.len(), 3);
1199    }
1200    #[test]
1201    fn new_series_from_arrow_primitive_array() {
1202        let array = UInt32Array::from_slice([1, 2, 3, 4, 5]);
1203        let array_ref: ArrayRef = Box::new(array);
1204
1205        let _ = Series::try_new("foo".into(), array_ref).unwrap();
1206    }
1207
1208    #[test]
1209    fn series_append() {
1210        let mut s1 = Series::new("a".into(), &[1, 2]);
1211        let s2 = Series::new("b".into(), &[3]);
1212        s1.append(&s2).unwrap();
1213        assert_eq!(s1.len(), 3);
1214
1215        // add wrong type
1216        let s2 = Series::new("b".into(), &[3.0]);
1217        assert!(s1.append(&s2).is_err())
1218    }
1219
1220    #[test]
1221    #[cfg(feature = "dtype-decimal")]
1222    fn series_append_decimal() {
1223        let s1 = Series::new("a".into(), &[1.1, 2.3])
1224            .cast(&DataType::Decimal(38, 2))
1225            .unwrap();
1226        let s2 = Series::new("b".into(), &[3])
1227            .cast(&DataType::Decimal(38, 0))
1228            .unwrap();
1229
1230        {
1231            let mut s1 = s1.clone();
1232            s1.append(&s2).unwrap();
1233            assert_eq!(s1.len(), 3);
1234            assert_eq!(s1.get(2).unwrap(), AnyValue::Decimal(300, 38, 2));
1235        }
1236
1237        {
1238            let mut s2 = s2;
1239            s2.extend(&s1).unwrap();
1240            assert_eq!(s2.get(2).unwrap(), AnyValue::Decimal(2, 38, 0));
1241        }
1242    }
1243
1244    #[test]
1245    fn series_slice_works() {
1246        let series = Series::new("a".into(), &[1i64, 2, 3, 4, 5]);
1247
1248        let slice_1 = series.slice(-3, 3);
1249        let slice_2 = series.slice(-5, 5);
1250        let slice_3 = series.slice(0, 5);
1251
1252        assert_eq!(slice_1.get(0).unwrap(), AnyValue::Int64(3));
1253        assert_eq!(slice_2.get(0).unwrap(), AnyValue::Int64(1));
1254        assert_eq!(slice_3.get(0).unwrap(), AnyValue::Int64(1));
1255    }
1256
1257    #[test]
1258    fn out_of_range_slice_does_not_panic() {
1259        let series = Series::new("a".into(), &[1i64, 2, 3, 4, 5]);
1260
1261        let _ = series.slice(-3, 4);
1262        let _ = series.slice(-6, 2);
1263        let _ = series.slice(4, 2);
1264    }
1265}