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;
38pub use from::*;
39pub use iterator::{SeriesIter, SeriesPhysIter};
40use num_traits::NumCast;
41use polars_error::feature_gated;
42use polars_utils::broadcast::BroadcastLength;
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    /// Returns a series with the given length.
356    ///
357    /// Errors if this series' length is not 1 and also not equal to the requested length.
358    pub fn broadcast_to(&self, length: usize) -> PolarsResult<Cow<'_, Self>> {
359        let len = self.len();
360        if len == length {
361            Ok(Cow::Borrowed(self))
362        } else if len == 1 {
363            Ok(Cow::Owned(self.new_from_index(0, length)))
364        } else {
365            polars_bail!(
366                ShapeMismatch: "can't broadcast Series '{}' of length {len} to length {length}",
367                self.name()
368            );
369        }
370    }
371
372    /// See broadcast_to.
373    pub fn broadcast_in_place_to(&mut self, length: usize) -> PolarsResult<()> {
374        if let Cow::Owned(new) = self.broadcast_to(length)? {
375            *self = new;
376        }
377        Ok(())
378    }
379
380    /// See broadcast_to.
381    pub fn broadcast_owned_to(mut self, length: usize) -> PolarsResult<Self> {
382        self.broadcast_in_place_to(length)?;
383        Ok(self)
384    }
385
386    /// Sort the series with specific options.
387    ///
388    /// # Example
389    ///
390    /// ```rust
391    /// # use polars_core::prelude::*;
392    /// # fn main() -> PolarsResult<()> {
393    /// let s = Series::new("foo".into(), [2, 1, 3]);
394    /// let sorted = s.sort(SortOptions::default())?;
395    /// assert_eq!(sorted, Series::new("foo".into(), [1, 2, 3]));
396    /// # Ok(())
397    /// }
398    /// ```
399    ///
400    /// See [`SortOptions`] for more options.
401    pub fn sort(&self, sort_options: SortOptions) -> PolarsResult<Self> {
402        self.sort_with(sort_options)
403    }
404
405    /// Only implemented for numeric types
406    pub fn as_single_ptr(&mut self) -> PolarsResult<usize> {
407        self._get_inner_mut().as_single_ptr()
408    }
409
410    pub fn cast(&self, dtype: &DataType) -> PolarsResult<Self> {
411        self.cast_with_options(dtype, CastOptions::NonStrict)
412    }
413
414    /// Cast [`Series`] to another [`DataType`].
415    pub fn cast_with_options(&self, dtype: &DataType, options: CastOptions) -> PolarsResult<Self> {
416        let slf = self
417            .trim_lists_to_normalized_offsets()
418            .map_or(Cow::Borrowed(self), Cow::Owned);
419        let slf = slf.propagate_nulls().map_or(slf, Cow::Owned);
420
421        use DataType as D;
422        let do_clone = match dtype {
423            D::Unknown(UnknownKind::Any) => true,
424            D::Unknown(UnknownKind::Int(_)) if slf.dtype().is_integer() => true,
425            D::Unknown(UnknownKind::Float) if slf.dtype().is_float() => true,
426            D::Unknown(UnknownKind::Str)
427                if slf.dtype().is_string() | slf.dtype().is_categorical() =>
428            {
429                true
430            },
431            dt if (dt.is_primitive() || dt.is_extension()) && dt == slf.dtype() => true,
432            _ => false,
433        };
434
435        if do_clone {
436            return Ok(slf.into_owned());
437        }
438
439        pub fn cast_dtype(dtype: &DataType) -> Option<DataType> {
440            match dtype {
441                D::Unknown(UnknownKind::Int(v)) => Some(materialize_dyn_int(*v).dtype()),
442                D::Unknown(UnknownKind::Float) => Some(DataType::Float64),
443                D::Unknown(UnknownKind::Str) => Some(DataType::String),
444                // Best leave as is.
445                D::List(inner) => cast_dtype(inner.as_ref()).map(Box::new).map(D::List),
446                #[cfg(feature = "dtype-struct")]
447                D::Struct(fields) => {
448                    // @NOTE: We only allocate if we really need to.
449
450                    let mut field_iter = fields.iter().enumerate();
451                    let mut new_fields = loop {
452                        let (i, field) = field_iter.next()?;
453
454                        if let Some(dtype) = cast_dtype(&field.dtype) {
455                            let mut new_fields = Vec::with_capacity(fields.len());
456                            new_fields.extend(fields.iter().take(i).cloned());
457                            new_fields.push(Field {
458                                name: field.name.clone(),
459                                dtype,
460                            });
461                            break new_fields;
462                        }
463                    };
464
465                    new_fields.extend(fields.iter().skip(new_fields.len()).cloned().map(|field| {
466                        let dtype = cast_dtype(&field.dtype).unwrap_or(field.dtype);
467                        Field {
468                            name: field.name,
469                            dtype,
470                        }
471                    }));
472
473                    Some(D::Struct(new_fields))
474                },
475                _ => None,
476            }
477        }
478
479        let mut casted = cast_dtype(dtype);
480        if dtype.is_list() && dtype.inner_dtype().is_some_and(|dt| dt.is_null()) {
481            if let Some(from_inner_dtype) = slf.dtype().inner_dtype() {
482                casted = Some(DataType::List(Box::new(from_inner_dtype.clone())));
483            }
484        }
485        let dtype = match casted {
486            None => dtype,
487            Some(ref dtype) => dtype,
488        };
489
490        // Always allow casting all nulls to other all nulls.
491        let len = slf.len();
492        if slf.null_count() == len {
493            return Ok(Series::full_null(slf.name().clone(), len, dtype));
494        }
495
496        let new_options = match options {
497            // Strictness is handled on this level to improve error messages, if not nested.
498            // Nested types could hide cast errors, so have to be done internally.
499            CastOptions::Strict if !dtype.is_nested() => CastOptions::NonStrict,
500            opt => opt,
501        };
502
503        let out = slf.0.cast(dtype, new_options)?;
504        if options.is_strict() {
505            handle_casting_failures(slf.as_ref(), &out)?;
506        }
507        Ok(out)
508    }
509
510    /// Cast from physical to logical types without any checks on the validity of the cast.
511    ///
512    /// # Safety
513    ///
514    /// This can lead to invalid memory access in downstream code.
515    pub unsafe fn cast_unchecked(&self, dtype: &DataType) -> PolarsResult<Self> {
516        match self.dtype() {
517            #[cfg(feature = "dtype-struct")]
518            DataType::Struct(_) => self.struct_().unwrap().cast_unchecked(dtype),
519            DataType::List(_) => self.list().unwrap().cast_unchecked(dtype),
520            dt if dt.is_primitive_numeric() => {
521                with_match_physical_numeric_polars_type!(dt, |$T| {
522                    let ca: &ChunkedArray<$T> = self.as_ref().as_ref().as_ref();
523                        ca.cast_unchecked(dtype)
524                })
525            },
526            DataType::Binary => self.binary().unwrap().cast_unchecked(dtype),
527            _ => self.cast_with_options(dtype, CastOptions::Overflowing),
528        }
529    }
530
531    /// Convert a non-logical series back into a logical series without casting.
532    ///
533    /// # Safety
534    ///
535    /// This can lead to invalid memory access in downstream code.
536    pub unsafe fn from_physical_unchecked(&self, dtype: &DataType) -> PolarsResult<Self> {
537        debug_assert!(!self.dtype().is_logical(), "{:?}", self.dtype());
538
539        if self.dtype() == dtype {
540            return Ok(self.clone());
541        }
542
543        use DataType as D;
544        match (self.dtype(), dtype) {
545            #[cfg(feature = "dtype-decimal")]
546            (D::Int128, D::Decimal(precision, scale)) => {
547                let ca = self.i128().unwrap();
548                Ok(ca
549                    .clone()
550                    .into_decimal_unchecked(*precision, *scale)
551                    .into_series())
552            },
553
554            #[cfg(feature = "dtype-categorical")]
555            (phys, D::Categorical(cats, _)) if &cats.physical().dtype() == phys => {
556                with_match_categorical_physical_type!(cats.physical(), |$C| {
557                    type CA = ChunkedArray<<$C as PolarsCategoricalType>::PolarsPhysical>;
558                    let ca = self.as_ref().as_any().downcast_ref::<CA>().unwrap();
559                    Ok(CategoricalChunked::<$C>::from_cats_and_dtype_unchecked(
560                        ca.clone(),
561                        dtype.clone(),
562                    )
563                    .into_series())
564                })
565            },
566            #[cfg(feature = "dtype-categorical")]
567            (phys, D::Enum(fcats, _)) if &fcats.physical().dtype() == phys => {
568                with_match_categorical_physical_type!(fcats.physical(), |$C| {
569                    type CA = ChunkedArray<<$C as PolarsCategoricalType>::PolarsPhysical>;
570                    let ca = self.as_ref().as_any().downcast_ref::<CA>().unwrap();
571                    Ok(CategoricalChunked::<$C>::from_cats_and_dtype_unchecked(
572                        ca.clone(),
573                        dtype.clone(),
574                    )
575                    .into_series())
576                })
577            },
578
579            (D::Int32, D::Date) => feature_gated!("dtype-time", Ok(self.clone().into_date())),
580            (D::Int64, D::Datetime(tu, tz)) => feature_gated!(
581                "dtype-datetime",
582                Ok(self.clone().into_datetime(*tu, tz.clone()))
583            ),
584            (D::Int64, D::Duration(tu)) => {
585                feature_gated!("dtype-duration", Ok(self.clone().into_duration(*tu)))
586            },
587            (D::Int64, D::Time) => feature_gated!("dtype-time", Ok(self.clone().into_time())),
588
589            (D::List(_), D::List(to)) => unsafe {
590                self.list()
591                    .unwrap()
592                    .from_physical_unchecked(to.as_ref().clone())
593                    .map(|ca| ca.into_series())
594            },
595            #[cfg(feature = "dtype-array")]
596            (D::Array(_, lw), D::Array(to, rw)) if lw == rw => unsafe {
597                self.array()
598                    .unwrap()
599                    .from_physical_unchecked(to.as_ref().clone())
600                    .map(|ca| ca.into_series())
601            },
602            #[cfg(feature = "dtype-struct")]
603            (D::Struct(_), D::Struct(to)) => unsafe {
604                self.struct_()
605                    .unwrap()
606                    .from_physical_unchecked(to.as_slice())
607                    .map(|ca| ca.into_series())
608            },
609
610            #[cfg(feature = "dtype-extension")]
611            (_, D::Extension(typ, storage)) => {
612                let storage_series = self.from_physical_unchecked(storage.as_ref())?;
613                let ext = ExtensionChunked::from_storage(typ.clone(), storage_series);
614                Ok(ext.into_series())
615            },
616
617            _ => panic!("invalid from_physical({dtype:?}) for {:?}", self.dtype()),
618        }
619    }
620
621    #[cfg(feature = "dtype-extension")]
622    pub fn into_extension(self, typ: ExtensionTypeInstance) -> Series {
623        assert!(!self.dtype().is_extension());
624        let ext = ExtensionChunked::from_storage(typ, self);
625        ext.into_series()
626    }
627
628    /// Cast numerical types to f64, and keep floats as is.
629    pub fn to_float(&self) -> PolarsResult<Series> {
630        match self.dtype() {
631            DataType::Float32 | DataType::Float64 => Ok(self.clone()),
632            _ => self.cast_with_options(&DataType::Float64, CastOptions::Overflowing),
633        }
634    }
635
636    /// Get the sum of the Series as a `Scalar`.
637    /// Returns a `Scalar` with a zeroed value if self is an empty numeric series.
638    ///
639    /// If the [`DataType`] is one of `{Int8, UInt8, Int16, UInt16}` the sum is
640    /// computed in an `Int64` accumulator and the result is returned as `Int64`
641    /// to prevent overflow issues.
642    pub fn sum<T>(&self) -> PolarsResult<T>
643    where
644        T: NumCast + IsFloat,
645    {
646        let sum = self.sum_reduce()?;
647        let sum = sum.value().extract().unwrap();
648        Ok(sum)
649    }
650
651    /// Returns the minimum value in the array, according to the natural order.
652    /// Returns an option because the array is nullable.
653    pub fn min<T>(&self) -> PolarsResult<Option<T>>
654    where
655        T: NumCast + IsFloat,
656    {
657        let min = self.min_reduce()?;
658        let min = min.value().extract::<T>();
659        Ok(min)
660    }
661
662    /// Returns the maximum value in the array, according to the natural order.
663    /// Returns an option because the array is nullable.
664    pub fn max<T>(&self) -> PolarsResult<Option<T>>
665    where
666        T: NumCast + IsFloat,
667    {
668        let max = self.max_reduce()?;
669        let max = max.value().extract::<T>();
670        Ok(max)
671    }
672
673    /// Explode a list Series. This expands every item to a new row..
674    pub fn explode(&self, options: ExplodeOptions) -> PolarsResult<Series> {
675        match self.dtype() {
676            DataType::List(_) => self.list().unwrap().explode(options),
677            #[cfg(feature = "dtype-array")]
678            DataType::Array(_, _) => self.array().unwrap().explode(options),
679            _ => Ok(self.clone()),
680        }
681    }
682
683    /// Check if numeric value is NaN (note this is different than missing/ null)
684    pub fn is_nan(&self) -> PolarsResult<BooleanChunked> {
685        match self.dtype() {
686            #[cfg(feature = "dtype-f16")]
687            DataType::Float16 => Ok(self.f16().unwrap().is_nan()),
688            DataType::Float32 => Ok(self.f32().unwrap().is_nan()),
689            DataType::Float64 => Ok(self.f64().unwrap().is_nan()),
690            DataType::Null => Ok(BooleanChunked::full_null(self.name().clone(), self.len())),
691            dt if dt.is_primitive_numeric() => {
692                let arr = BooleanArray::full(self.len(), false, ArrowDataType::Boolean)
693                    .with_validity(self.rechunk_validity());
694                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
695            },
696            _ => polars_bail!(opq = is_nan, self.dtype()),
697        }
698    }
699
700    /// Check if numeric value is NaN (note this is different than missing/null)
701    pub fn is_not_nan(&self) -> PolarsResult<BooleanChunked> {
702        match self.dtype() {
703            #[cfg(feature = "dtype-f16")]
704            DataType::Float16 => Ok(self.f16().unwrap().is_not_nan()),
705            DataType::Float32 => Ok(self.f32().unwrap().is_not_nan()),
706            DataType::Float64 => Ok(self.f64().unwrap().is_not_nan()),
707            dt if dt.is_primitive_numeric() => {
708                let arr = BooleanArray::full(self.len(), true, ArrowDataType::Boolean)
709                    .with_validity(self.rechunk_validity());
710                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
711            },
712            _ => polars_bail!(opq = is_not_nan, self.dtype()),
713        }
714    }
715
716    /// Check if numeric value is finite
717    pub fn is_finite(&self) -> PolarsResult<BooleanChunked> {
718        match self.dtype() {
719            #[cfg(feature = "dtype-f16")]
720            DataType::Float16 => Ok(self.f16().unwrap().is_finite()),
721            DataType::Float32 => Ok(self.f32().unwrap().is_finite()),
722            DataType::Float64 => Ok(self.f64().unwrap().is_finite()),
723            DataType::Null => Ok(BooleanChunked::full_null(self.name().clone(), self.len())),
724            dt if dt.is_primitive_numeric() => {
725                let arr = BooleanArray::full(self.len(), true, ArrowDataType::Boolean)
726                    .with_validity(self.rechunk_validity());
727                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
728            },
729            _ => polars_bail!(opq = is_finite, self.dtype()),
730        }
731    }
732
733    /// Check if numeric value is infinite
734    pub fn is_infinite(&self) -> PolarsResult<BooleanChunked> {
735        match self.dtype() {
736            #[cfg(feature = "dtype-f16")]
737            DataType::Float16 => Ok(self.f16().unwrap().is_infinite()),
738            DataType::Float32 => Ok(self.f32().unwrap().is_infinite()),
739            DataType::Float64 => Ok(self.f64().unwrap().is_infinite()),
740            DataType::Null => Ok(BooleanChunked::full_null(self.name().clone(), self.len())),
741            dt if dt.is_primitive_numeric() => {
742                let arr = BooleanArray::full(self.len(), false, ArrowDataType::Boolean)
743                    .with_validity(self.rechunk_validity());
744                Ok(BooleanChunked::with_chunk(self.name().clone(), arr))
745            },
746            _ => polars_bail!(opq = is_infinite, self.dtype()),
747        }
748    }
749
750    /// Create a new ChunkedArray with values from self where the mask evaluates `true` and values
751    /// from `other` where the mask evaluates `false`. This function automatically broadcasts unit
752    /// length inputs.
753    #[cfg(feature = "zip_with")]
754    pub fn zip_with(&self, mask: &BooleanChunked, other: &Series) -> PolarsResult<Series> {
755        let (lhs, rhs) = coerce_lhs_rhs(self, other)?;
756        lhs.zip_with_same_type(mask, rhs.as_ref())
757    }
758
759    /// Converts a Series to their physical representation, if they have one,
760    /// otherwise the series is left unchanged.
761    ///
762    /// * Date -> Int32
763    /// * Datetime -> Int64
764    /// * Duration -> Int64
765    /// * Decimal -> Int128
766    /// * Time -> Int64
767    /// * Categorical -> U8/U16/U32
768    /// * List(inner) -> List(physical of inner)
769    /// * Array(inner) -> Array(physical of inner)
770    /// * Struct -> Struct with physical repr of each struct column
771    /// * Extension -> physical of storage type
772    pub fn to_physical_repr(&self) -> Cow<'_, Series> {
773        use DataType::*;
774        match self.dtype() {
775            // NOTE: Don't use cast here, as it might rechunk (if all nulls)
776            // which is not allowed in a phys repr.
777            #[cfg(feature = "dtype-date")]
778            Date => Cow::Owned(self.date().unwrap().phys.clone().into_series()),
779            #[cfg(feature = "dtype-datetime")]
780            Datetime(_, _) => Cow::Owned(self.datetime().unwrap().phys.clone().into_series()),
781            #[cfg(feature = "dtype-duration")]
782            Duration(_) => Cow::Owned(self.duration().unwrap().phys.clone().into_series()),
783            #[cfg(feature = "dtype-time")]
784            Time => Cow::Owned(self.time().unwrap().phys.clone().into_series()),
785            #[cfg(feature = "dtype-categorical")]
786            dt @ (Categorical(_, _) | Enum(_, _)) => {
787                with_match_categorical_physical_type!(dt.cat_physical().unwrap(), |$C| {
788                    let ca = self.cat::<$C>().unwrap();
789                    Cow::Owned(ca.physical().clone().into_series())
790                })
791            },
792            #[cfg(feature = "dtype-decimal")]
793            Decimal(_, _) => Cow::Owned(self.decimal().unwrap().phys.clone().into_series()),
794            List(_) => match self.list().unwrap().to_physical_repr() {
795                Cow::Borrowed(_) => Cow::Borrowed(self),
796                Cow::Owned(ca) => Cow::Owned(ca.into_series()),
797            },
798            #[cfg(feature = "dtype-array")]
799            Array(_, _) => match self.array().unwrap().to_physical_repr() {
800                Cow::Borrowed(_) => Cow::Borrowed(self),
801                Cow::Owned(ca) => Cow::Owned(ca.into_series()),
802            },
803            #[cfg(feature = "dtype-struct")]
804            Struct(_) => match self.struct_().unwrap().to_physical_repr() {
805                Cow::Borrowed(_) => Cow::Borrowed(self),
806                Cow::Owned(ca) => Cow::Owned(ca.into_series()),
807            },
808            #[cfg(feature = "dtype-extension")]
809            Extension(_, _) => self.ext().unwrap().storage().to_physical_repr(),
810            _ => Cow::Borrowed(self),
811        }
812    }
813
814    /// If the Series is an Extension type, return its storage Series.
815    /// Otherwise, return itself.
816    pub fn to_storage(&self) -> &Series {
817        #[cfg(feature = "dtype-extension")]
818        {
819            if let DataType::Extension(_, _) = self.dtype() {
820                return self.ext().unwrap().storage();
821            }
822        }
823        self
824    }
825
826    /// Traverse and collect every nth element in a new array.
827    pub fn gather_every(&self, n: usize, offset: usize) -> PolarsResult<Series> {
828        polars_ensure!(n > 0, ComputeError: "cannot perform gather every for `n=0`");
829        let idx = ((offset as IdxSize)..self.len() as IdxSize)
830            .step_by(n)
831            .collect_ca(PlSmallStr::EMPTY);
832        // SAFETY: we stay in-bounds.
833        Ok(unsafe { self.take_unchecked(&idx) })
834    }
835
836    #[cfg(feature = "dot_product")]
837    pub fn dot(&self, other: &Series) -> PolarsResult<f64> {
838        std::ops::Mul::mul(self, other)?.sum::<f64>()
839    }
840
841    /// Get the sum of the [`ChunkedArray`] as a `Scalar`.
842    /// Returns a `Scalar` with a single zeroed value if self is an empty numeric series.
843    ///
844    /// If the [`DataType`] is one of `{Int8, UInt8, Int16, UInt16}` the sum is
845    /// computed in an `Int64` accumulator and the result is returned as `Int64`
846    /// to prevent overflow issues.
847    pub fn sum_reduce(&self) -> PolarsResult<Scalar> {
848        self.0.sum_reduce()
849    }
850
851    /// Get the mean of the Series as a new Series of length 1.
852    /// Returns a Series with a single null entry if self is an empty numeric series.
853    pub fn mean_reduce(&self) -> PolarsResult<Scalar> {
854        self.0.mean_reduce()
855    }
856
857    /// Get the product of an array.
858    ///
859    /// If the [`DataType`] is one of `{Int8, UInt8, Int16, UInt16}` the `Series` is
860    /// first cast to `Int64` to prevent overflow issues.
861    pub fn product(&self) -> PolarsResult<Scalar> {
862        #[cfg(feature = "product")]
863        {
864            use DataType::*;
865            match self.dtype() {
866                Boolean => self.cast(&DataType::Int64).unwrap().product(),
867                Int8 | UInt8 | Int16 | UInt16 | Int32 | UInt32 => {
868                    let s = self.cast(&Int64).unwrap();
869                    s.product()
870                },
871                Int64 => Ok(self.i64().unwrap().prod_reduce()),
872                UInt64 => Ok(self.u64().unwrap().prod_reduce()),
873                #[cfg(feature = "dtype-i128")]
874                Int128 => Ok(self.i128().unwrap().prod_reduce()),
875                #[cfg(feature = "dtype-u128")]
876                UInt128 => Ok(self.u128().unwrap().prod_reduce()),
877                #[cfg(feature = "dtype-f16")]
878                Float16 => Ok(self.f16().unwrap().prod_reduce()),
879                Float32 => Ok(self.f32().unwrap().prod_reduce()),
880                Float64 => Ok(self.f64().unwrap().prod_reduce()),
881                #[cfg(feature = "dtype-decimal")]
882                Decimal(..) => Ok(self.decimal().unwrap().prod_reduce()),
883                dt => {
884                    polars_bail!(InvalidOperation: "`product` operation not supported for dtype `{dt}`")
885                },
886            }
887        }
888        #[cfg(not(feature = "product"))]
889        {
890            panic!("activate 'product' feature")
891        }
892    }
893
894    /// Cast throws an error if conversion had overflows
895    pub fn strict_cast(&self, dtype: &DataType) -> PolarsResult<Series> {
896        self.cast_with_options(dtype, CastOptions::Strict)
897    }
898
899    #[cfg(feature = "dtype-decimal")]
900    pub fn into_decimal(self, precision: usize, scale: usize) -> PolarsResult<Series> {
901        match self.dtype() {
902            DataType::Int128 => Ok(self
903                .i128()
904                .unwrap()
905                .clone()
906                .into_decimal(precision, scale)?
907                .into_series()),
908            DataType::Decimal(cur_prec, cur_scale)
909                if scale == *cur_scale && precision >= *cur_prec =>
910            {
911                Ok(self)
912            },
913            dt => panic!("into_decimal({precision:?}, {scale}) not implemented for {dt:?}"),
914        }
915    }
916
917    #[cfg(feature = "dtype-time")]
918    pub fn into_time(self) -> Series {
919        match self.dtype() {
920            DataType::Int64 => self.i64().unwrap().clone().into_time().into_series(),
921            DataType::Time => self
922                .time()
923                .unwrap()
924                .physical()
925                .clone()
926                .into_time()
927                .into_series(),
928            dt => panic!("date not implemented for {dt:?}"),
929        }
930    }
931
932    pub fn into_date(self) -> Series {
933        #[cfg(not(feature = "dtype-date"))]
934        {
935            panic!("activate feature dtype-date")
936        }
937        #[cfg(feature = "dtype-date")]
938        match self.dtype() {
939            DataType::Int32 => self.i32().unwrap().clone().into_date().into_series(),
940            DataType::Date => self
941                .date()
942                .unwrap()
943                .physical()
944                .clone()
945                .into_date()
946                .into_series(),
947            dt => panic!("date not implemented for {dt:?}"),
948        }
949    }
950
951    #[allow(unused_variables)]
952    pub fn into_datetime(self, timeunit: TimeUnit, tz: Option<TimeZone>) -> Series {
953        #[cfg(not(feature = "dtype-datetime"))]
954        {
955            panic!("activate feature dtype-datetime")
956        }
957
958        #[cfg(feature = "dtype-datetime")]
959        match self.dtype() {
960            DataType::Int64 => self
961                .i64()
962                .unwrap()
963                .clone()
964                .into_datetime(timeunit, tz)
965                .into_series(),
966            DataType::Datetime(_, _) => self
967                .datetime()
968                .unwrap()
969                .physical()
970                .clone()
971                .into_datetime(timeunit, tz)
972                .into_series(),
973            dt => panic!("into_datetime not implemented for {dt:?}"),
974        }
975    }
976
977    #[allow(unused_variables)]
978    pub fn into_duration(self, timeunit: TimeUnit) -> Series {
979        #[cfg(not(feature = "dtype-duration"))]
980        {
981            panic!("activate feature dtype-duration")
982        }
983        #[cfg(feature = "dtype-duration")]
984        match self.dtype() {
985            DataType::Int64 => self
986                .i64()
987                .unwrap()
988                .clone()
989                .into_duration(timeunit)
990                .into_series(),
991            DataType::Duration(_) => self
992                .duration()
993                .unwrap()
994                .physical()
995                .clone()
996                .into_duration(timeunit)
997                .into_series(),
998            dt => panic!("into_duration not implemented for {dt:?}"),
999        }
1000    }
1001
1002    // used for formatting
1003    pub fn str_value(&self, index: usize) -> PolarsResult<Cow<'_, str>> {
1004        Ok(self.0.get(index)?.str_value())
1005    }
1006    /// Get the head of the Series.
1007    pub fn head(&self, length: Option<usize>) -> Series {
1008        let len = length.unwrap_or(HEAD_DEFAULT_LENGTH);
1009        self.slice(0, std::cmp::min(len, self.len()))
1010    }
1011
1012    /// Get the tail of the Series.
1013    pub fn tail(&self, length: Option<usize>) -> Series {
1014        let len = length.unwrap_or(TAIL_DEFAULT_LENGTH);
1015        let len = std::cmp::min(len, self.len());
1016        self.slice(-(len as i64), len)
1017    }
1018
1019    /// Compute the unique elements, but maintain order. This requires more work
1020    /// than a naive [`Series::unique`](SeriesTrait::unique).
1021    pub fn unique_stable(&self) -> PolarsResult<Series> {
1022        let idx = self.arg_unique()?;
1023        // SAFETY: Indices are in bounds.
1024        unsafe { Ok(self.take_unchecked(&idx)) }
1025    }
1026
1027    pub fn try_idx(&self) -> Option<&IdxCa> {
1028        #[cfg(feature = "bigidx")]
1029        {
1030            self.try_u64()
1031        }
1032        #[cfg(not(feature = "bigidx"))]
1033        {
1034            self.try_u32()
1035        }
1036    }
1037
1038    pub fn idx(&self) -> PolarsResult<&IdxCa> {
1039        #[cfg(feature = "bigidx")]
1040        {
1041            self.u64()
1042        }
1043        #[cfg(not(feature = "bigidx"))]
1044        {
1045            self.u32()
1046        }
1047    }
1048
1049    /// Returns an estimation of the total (heap) allocated size of the `Series` in bytes.
1050    ///
1051    /// # Implementation
1052    /// This estimation is the sum of the size of its buffers, validity, including nested arrays.
1053    /// Multiple arrays may share buffers and bitmaps. Therefore, the size of 2 arrays is not the
1054    /// sum of the sizes computed from this function. In particular, [`StructArray`]'s size is an upper bound.
1055    ///
1056    /// When an array is sliced, its allocated size remains constant because the buffer unchanged.
1057    /// However, this function will yield a smaller number. This is because this function returns
1058    /// the visible size of the buffer, not its total capacity.
1059    ///
1060    /// FFI buffers are included in this estimation.
1061    pub fn estimated_size(&self) -> usize {
1062        let mut size = 0;
1063        match self.dtype() {
1064            // TODO @ cat-rework: include mapping size here?
1065            #[cfg(feature = "object")]
1066            DataType::Object(_) => {
1067                let ArrowDataType::FixedSizeBinary(size) = self.chunks()[0].dtype() else {
1068                    unreachable!()
1069                };
1070                // This is only the pointer size in python. So will be a huge underestimation.
1071                return self.len() * *size;
1072            },
1073            _ => {},
1074        }
1075
1076        size += self
1077            .chunks()
1078            .iter()
1079            .map(|arr| estimated_bytes_size(&**arr))
1080            .sum::<usize>();
1081
1082        size
1083    }
1084
1085    pub fn row_encode_unordered(&self) -> PolarsResult<BinaryOffsetChunked> {
1086        row_encode::_get_rows_encoded_ca_unordered(
1087            self.name().clone(),
1088            &[self.clone().into_column()],
1089        )
1090    }
1091
1092    pub fn row_encode_ordered(
1093        &self,
1094        descending: bool,
1095        nulls_last: bool,
1096    ) -> PolarsResult<BinaryOffsetChunked> {
1097        row_encode::_get_rows_encoded_ca(
1098            self.name().clone(),
1099            &[self.clone().into_column()],
1100            &[descending],
1101            &[nulls_last],
1102            false,
1103        )
1104    }
1105}
1106
1107impl Default for Series {
1108    fn default() -> Self {
1109        NullChunked::new(PlSmallStr::EMPTY, 0).into_series()
1110    }
1111}
1112
1113impl Deref for Series {
1114    type Target = dyn SeriesTrait;
1115
1116    fn deref(&self) -> &Self::Target {
1117        self.0.as_ref()
1118    }
1119}
1120
1121impl<'a> AsRef<dyn SeriesTrait + 'a> for Series {
1122    fn as_ref(&self) -> &(dyn SeriesTrait + 'a) {
1123        self.0.as_ref()
1124    }
1125}
1126
1127impl<T: PolarsPhysicalType> AsRef<ChunkedArray<T>> for dyn SeriesTrait + '_ {
1128    fn as_ref(&self) -> &ChunkedArray<T> {
1129        // @NOTE: SeriesTrait `as_any` returns a std::any::Any for the underlying ChunkedArray /
1130        // Logical (so not the SeriesWrap).
1131        let Some(ca) = self.as_any().downcast_ref::<ChunkedArray<T>>() else {
1132            panic!(
1133                "implementation error, cannot get ref {:?} from {:?}",
1134                T::get_static_dtype(),
1135                self.dtype()
1136            );
1137        };
1138
1139        ca
1140    }
1141}
1142
1143impl<T: PolarsPhysicalType> AsMut<ChunkedArray<T>> for dyn SeriesTrait + '_ {
1144    fn as_mut(&mut self) -> &mut ChunkedArray<T> {
1145        if !self.as_any_mut().is::<ChunkedArray<T>>() {
1146            panic!(
1147                "implementation error, cannot get ref {:?} from {:?}",
1148                T::get_static_dtype(),
1149                self.dtype()
1150            );
1151        }
1152
1153        // @NOTE: SeriesTrait `as_any` returns a std::any::Any for the underlying ChunkedArray /
1154        // Logical (so not the SeriesWrap).
1155        self.as_any_mut().downcast_mut::<ChunkedArray<T>>().unwrap()
1156    }
1157}
1158
1159impl BroadcastLength for Series {
1160    fn _broadcast_len(&self) -> usize {
1161        self.len()
1162    }
1163
1164    fn _column_name(&self) -> Option<&str> {
1165        Some(self.name())
1166    }
1167}
1168
1169#[cfg(test)]
1170mod test {
1171    use crate::prelude::*;
1172    use crate::series::*;
1173
1174    #[test]
1175    fn cast() {
1176        let ar = UInt32Chunked::new("a".into(), &[1, 2]);
1177        let s = ar.into_series();
1178        let s2 = s.cast(&DataType::Int64).unwrap();
1179
1180        assert!(s2.i64().is_ok());
1181        let s2 = s.cast(&DataType::Float32).unwrap();
1182        assert!(s2.f32().is_ok());
1183    }
1184
1185    #[test]
1186    fn new_series() {
1187        let _ = Series::new("boolean series".into(), &vec![true, false, true]);
1188        let _ = Series::new("int series".into(), &[1, 2, 3]);
1189        let ca = Int32Chunked::new("a".into(), &[1, 2, 3]);
1190        let _ = ca.into_series();
1191    }
1192
1193    #[test]
1194    #[cfg(feature = "dtype-date")]
1195    fn roundtrip_list_logical_20311() {
1196        let list = ListChunked::from_chunk_iter(
1197            PlSmallStr::from_static("a"),
1198            [ListArray::new(
1199                ArrowDataType::LargeList(Box::new(ArrowField::new(
1200                    LIST_VALUES_NAME,
1201                    ArrowDataType::Int32,
1202                    true,
1203                ))),
1204                unsafe { arrow::offset::Offsets::new_unchecked(vec![0, 1]) }.into(),
1205                PrimitiveArray::new(ArrowDataType::Int32, vec![1i32].into(), None).to_boxed(),
1206                None,
1207            )],
1208        );
1209        let list = unsafe { list.from_physical_unchecked(DataType::Date) }.unwrap();
1210        assert_eq!(list.dtype(), &DataType::List(Box::new(DataType::Date)));
1211    }
1212
1213    #[test]
1214    #[cfg(feature = "dtype-struct")]
1215    fn new_series_from_empty_structs() {
1216        let dtype = DataType::Struct(vec![]);
1217        let empties = vec![AnyValue::StructOwned(Box::new((vec![], vec![]))); 3];
1218        let s = Series::from_any_values_and_dtype("".into(), &empties, &dtype, false).unwrap();
1219        assert_eq!(s.len(), 3);
1220    }
1221    #[test]
1222    fn new_series_from_arrow_primitive_array() {
1223        let array = UInt32Array::from_slice([1, 2, 3, 4, 5]);
1224        let array_ref: ArrayRef = Box::new(array);
1225
1226        let _ = Series::try_new("foo".into(), array_ref).unwrap();
1227    }
1228
1229    #[test]
1230    fn series_append() {
1231        let mut s1 = Series::new("a".into(), &[1, 2]);
1232        let s2 = Series::new("b".into(), &[3]);
1233        s1.append(&s2).unwrap();
1234        assert_eq!(s1.len(), 3);
1235
1236        // add wrong type
1237        let s2 = Series::new("b".into(), &[3.0]);
1238        assert!(s1.append(&s2).is_err())
1239    }
1240
1241    #[test]
1242    #[cfg(feature = "dtype-decimal")]
1243    fn series_append_decimal() {
1244        let s1 = Series::new("a".into(), &[1.1, 2.3])
1245            .cast(&DataType::Decimal(38, 2))
1246            .unwrap();
1247        let s2 = Series::new("b".into(), &[3])
1248            .cast(&DataType::Decimal(38, 0))
1249            .unwrap();
1250
1251        {
1252            let mut s1 = s1.clone();
1253            s1.append(&s2).unwrap();
1254            assert_eq!(s1.len(), 3);
1255            assert_eq!(s1.get(2).unwrap(), AnyValue::Decimal(300, 38, 2));
1256        }
1257
1258        {
1259            let mut s2 = s2;
1260            s2.extend(&s1).unwrap();
1261            assert_eq!(s2.get(2).unwrap(), AnyValue::Decimal(2, 38, 0));
1262        }
1263    }
1264
1265    #[test]
1266    fn series_slice_works() {
1267        let series = Series::new("a".into(), &[1i64, 2, 3, 4, 5]);
1268
1269        let slice_1 = series.slice(-3, 3);
1270        let slice_2 = series.slice(-5, 5);
1271        let slice_3 = series.slice(0, 5);
1272
1273        assert_eq!(slice_1.get(0).unwrap(), AnyValue::Int64(3));
1274        assert_eq!(slice_2.get(0).unwrap(), AnyValue::Int64(1));
1275        assert_eq!(slice_3.get(0).unwrap(), AnyValue::Int64(1));
1276    }
1277
1278    #[test]
1279    fn out_of_range_slice_does_not_panic() {
1280        let series = Series::new("a".into(), &[1i64, 2, 3, 4, 5]);
1281
1282        let _ = series.slice(-3, 4);
1283        let _ = series.slice(-6, 2);
1284        let _ = series.slice(4, 2);
1285    }
1286}