Skip to main content

polars_core/series/
series_trait.rs

1use std::any::Any;
2use std::borrow::Cow;
3
4use polars_arrow::bitmap::{Bitmap, BitmapBuilder};
5use polars_arrow::compute::utils::combine_validities_and;
6use polars_compute::rolling::QuantileMethod;
7
8use crate::chunked_array::cast::CastOptions;
9#[cfg(feature = "object")]
10use crate::chunked_array::object::PolarsObjectSafe;
11use crate::prelude::*;
12use crate::utils::{first_non_null, last_non_null};
13
14#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
15pub enum IsSorted {
16    Ascending,
17    Descending,
18    Not,
19}
20
21impl IsSorted {
22    pub fn reverse(self) -> Self {
23        use IsSorted::*;
24        match self {
25            Ascending => Descending,
26            Descending => Ascending,
27            Not => Not,
28        }
29    }
30}
31
32pub enum BitRepr {
33    U8(UInt8Chunked),
34    U16(UInt16Chunked),
35    U32(UInt32Chunked),
36    U64(UInt64Chunked),
37    #[cfg(feature = "dtype-u128")]
38    U128(UInt128Chunked),
39}
40
41pub(crate) mod private {
42    use polars_utils::aliases::PlSeedableRandomStateQuality;
43
44    use super::*;
45    use crate::chunked_array::flags::StatisticsFlags;
46    use crate::chunked_array::ops::compare_inner::TotalOrdInner;
47
48    pub trait PrivateSeriesNumeric {
49        /// Return a bit representation
50        ///
51        /// If there is no available bit representation this returns `None`.
52        fn bit_repr(&self) -> Option<BitRepr>;
53    }
54
55    pub trait PrivateSeries {
56        #[cfg(feature = "object")]
57        fn get_list_builder(
58            &self,
59            _name: PlSmallStr,
60            _values_capacity: usize,
61            _list_capacity: usize,
62        ) -> Box<dyn ListBuilderTrait> {
63            invalid_operation_panic!(get_list_builder, self)
64        }
65
66        /// Get field (used in schema)
67        fn _field(&self) -> Cow<'_, Field>;
68
69        fn _dtype(&self) -> &DataType;
70
71        fn compute_len(&mut self);
72
73        fn _get_flags(&self) -> StatisticsFlags;
74
75        fn _set_flags(&mut self, flags: StatisticsFlags);
76
77        #[expect(clippy::wrong_self_convention)]
78        fn into_total_ord_inner<'a>(&'a self) -> Box<dyn TotalOrdInner + 'a>;
79
80        fn vec_hash(
81            &self,
82            _build_hasher: PlSeedableRandomStateQuality,
83            _buf: &mut Vec<u64>,
84        ) -> PolarsResult<()>;
85        fn vec_hash_combine(
86            &self,
87            _build_hasher: PlSeedableRandomStateQuality,
88            _hashes: &mut [u64],
89        ) -> PolarsResult<()>;
90
91        /// # Safety
92        ///
93        /// Does no bounds checks, groups must be correct.
94        #[cfg(feature = "algorithm_group_by")]
95        unsafe fn agg_min(&self, groups: &GroupsType) -> Series {
96            Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
97        }
98        /// # Safety
99        ///
100        /// Does no bounds checks, groups must be correct.
101        #[cfg(feature = "algorithm_group_by")]
102        unsafe fn agg_max(&self, groups: &GroupsType) -> Series {
103            Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
104        }
105        /// # Safety
106        ///
107        /// Does no bounds checks, groups must be correct.
108        #[cfg(feature = "algorithm_group_by")]
109        unsafe fn agg_arg_min(&self, groups: &GroupsType) -> Series {
110            Series::full_null(self._field().name().clone(), groups.len(), &IDX_DTYPE)
111        }
112
113        /// # Safety
114        ///
115        /// Does no bounds checks, groups must be correct.
116        #[cfg(feature = "algorithm_group_by")]
117        unsafe fn agg_arg_max(&self, groups: &GroupsType) -> Series {
118            Series::full_null(self._field().name().clone(), groups.len(), &IDX_DTYPE)
119        }
120
121        /// If the [`DataType`] is one of `{Int8, UInt8, Int16, UInt16}` the `Series` is
122        /// first cast to `Int64` to prevent overflow issues.
123        #[cfg(feature = "algorithm_group_by")]
124        unsafe fn agg_sum(&self, groups: &GroupsType) -> Series {
125            Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
126        }
127        /// # Safety
128        ///
129        /// Does no bounds checks, groups must be correct.
130        #[cfg(feature = "algorithm_group_by")]
131        unsafe fn agg_std(&self, groups: &GroupsType, _ddof: u8) -> Series {
132            Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
133        }
134        /// # Safety
135        ///
136        /// Does no bounds checks, groups must be correct.
137        #[cfg(feature = "algorithm_group_by")]
138        unsafe fn agg_var(&self, groups: &GroupsType, _ddof: u8) -> Series {
139            Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
140        }
141        /// # Safety
142        ///
143        /// Does no bounds checks, groups must be correct.
144        #[cfg(feature = "algorithm_group_by")]
145        unsafe fn agg_list(&self, groups: &GroupsType) -> Series {
146            Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
147        }
148
149        /// # Safety
150        ///
151        /// Does no bounds checks, groups must be correct.
152        #[cfg(feature = "bitwise")]
153        unsafe fn agg_and(&self, groups: &GroupsType) -> Series {
154            Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
155        }
156
157        /// # Safety
158        ///
159        /// Does no bounds checks, groups must be correct.
160        #[cfg(feature = "bitwise")]
161        unsafe fn agg_or(&self, groups: &GroupsType) -> Series {
162            Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
163        }
164
165        /// # Safety
166        ///
167        /// Does no bounds checks, groups must be correct.
168        #[cfg(feature = "bitwise")]
169        unsafe fn agg_xor(&self, groups: &GroupsType) -> Series {
170            Series::full_null(self._field().name().clone(), groups.len(), self._dtype())
171        }
172
173        fn subtract(&self, _rhs: &Series) -> PolarsResult<Series> {
174            polars_bail!(opq = subtract, self._dtype());
175        }
176        fn add_to(&self, _rhs: &Series) -> PolarsResult<Series> {
177            polars_bail!(opq = add, self._dtype());
178        }
179        fn multiply(&self, _rhs: &Series) -> PolarsResult<Series> {
180            polars_bail!(opq = multiply, self._dtype());
181        }
182        fn divide(&self, _rhs: &Series) -> PolarsResult<Series> {
183            polars_bail!(opq = divide, self._dtype());
184        }
185        fn remainder(&self, _rhs: &Series) -> PolarsResult<Series> {
186            polars_bail!(opq = remainder, self._dtype());
187        }
188        #[cfg(feature = "algorithm_group_by")]
189        fn group_tuples(&self, _multithreaded: bool, _sorted: bool) -> PolarsResult<GroupsType> {
190            polars_bail!(opq = group_tuples, self._dtype());
191        }
192        #[cfg(feature = "zip_with")]
193        fn zip_with_same_type(
194            &self,
195            _mask: &BooleanChunked,
196            _other: &Series,
197        ) -> PolarsResult<Series> {
198            polars_bail!(opq = zip_with_same_type, self._dtype());
199        }
200
201        #[allow(unused_variables)]
202        fn arg_sort_multiple(
203            &self,
204            by: &[Column],
205            _options: &SortMultipleOptions,
206        ) -> PolarsResult<IdxCa> {
207            polars_bail!(opq = arg_sort_multiple, self._dtype());
208        }
209    }
210}
211
212pub trait SeriesTrait:
213    Send + Sync + private::PrivateSeries + private::PrivateSeriesNumeric
214{
215    /// Rename the Series.
216    fn rename(&mut self, name: PlSmallStr);
217
218    /// Get the lengths of the underlying chunks
219    fn chunk_lengths(&self) -> ChunkLenIter<'_>;
220
221    /// Name of series.
222    fn name(&self) -> &PlSmallStr;
223
224    /// Get field (used in schema)
225    fn field(&self) -> Cow<'_, Field> {
226        self._field()
227    }
228
229    /// Get datatype of series.
230    #[inline(always)]
231    fn dtype(&self) -> &DataType {
232        self._dtype()
233    }
234
235    /// Underlying chunks.
236    fn chunks(&self) -> &Vec<ArrayRef>;
237
238    /// Underlying chunks.
239    ///
240    /// # Safety
241    /// The caller must ensure the length and the data types of `ArrayRef` does not change.
242    unsafe fn chunks_mut(&mut self) -> &mut Vec<ArrayRef>;
243
244    /// Number of chunks in this Series
245    fn n_chunks(&self) -> usize {
246        self.chunks().len()
247    }
248
249    /// Shrink the capacity of this array to fit its length.
250    fn shrink_to_fit(&mut self) {
251        // no-op
252    }
253
254    /// Take `num_elements` from the top as a zero copy view.
255    fn limit(&self, num_elements: usize) -> Series {
256        self.slice(Slice::head(num_elements))
257    }
258
259    /// Get a zero copy view of the elements `slice` selects.
260    fn slice(&self, _slice: Slice) -> Series;
261
262    /// Get a zero copy view of the data.
263    ///
264    /// When offset is negative the offset is counted from the
265    /// end of the array
266    fn split_at(&self, _offset: i64) -> (Series, Series);
267
268    fn append(&mut self, other: &Series) -> PolarsResult<()>;
269    fn append_owned(&mut self, other: Series) -> PolarsResult<()>;
270
271    #[doc(hidden)]
272    fn extend(&mut self, _other: &Series) -> PolarsResult<()>;
273
274    /// Filter by boolean mask. This operation clones data.
275    fn filter(&self, _filter: &BooleanChunked) -> PolarsResult<Series>;
276
277    /// Take from `self` at the indexes given by `idx`.
278    ///
279    /// Null values in `idx` become null values in the output array.
280    ///
281    /// This operation is clone.
282    fn take(&self, _indices: &IdxCa) -> PolarsResult<Series>;
283
284    /// Take from `self` at the indexes given by `idx`.
285    ///
286    /// Null values in `idx` become null values in the output array.
287    ///
288    /// # Safety
289    /// This doesn't check any bounds.
290    unsafe fn take_unchecked(&self, _idx: &IdxCa) -> Series;
291
292    /// Take from `self` at the indexes given by `idx`.
293    ///
294    /// This operation is clone.
295    fn take_slice(&self, _indices: &[IdxSize]) -> PolarsResult<Series>;
296
297    /// Take from `self` at the indexes given by `idx`.
298    ///
299    /// # Safety
300    /// This doesn't check any bounds.
301    unsafe fn take_slice_unchecked(&self, _idx: &[IdxSize]) -> Series;
302
303    /// Get length of series.
304    fn len(&self) -> usize;
305
306    /// Check if Series is empty.
307    fn is_empty(&self) -> bool {
308        self.len() == 0
309    }
310
311    /// Check if Series only consists of nulls.
312    fn is_full_null(&self) -> bool {
313        self.len() == self.null_count()
314    }
315
316    /// Aggregate all chunks to a contiguous array of memory.
317    fn rechunk(&self) -> Series;
318
319    /// Returns the validity of this series as a single bitmap.
320    fn rechunk_validity(&self) -> Option<Bitmap> {
321        if self.chunks().len() == 1 {
322            return self.chunks()[0].validity().cloned();
323        }
324
325        if !self.has_nulls() || self.is_empty() {
326            return None;
327        }
328
329        let mut bm = BitmapBuilder::with_capacity(self.len());
330        for arr in self.chunks() {
331            if let Some(v) = arr.validity() {
332                bm.extend_from_bitmap(v);
333            } else {
334                bm.extend_constant(arr.len(), true);
335            }
336        }
337        bm.into_opt_validity()
338    }
339
340    /// Sets the validity mask of this Series to the given bitmap.
341    fn with_validity(&self, validity: Option<Bitmap>) -> Series;
342
343    /// Applies the given mask to this Series, returning a new Series. If a
344    /// validity bit is true nothing changes, if it is false the corresponding
345    /// element becomes null.
346    fn mask(&self, validity: &Bitmap) -> Series {
347        if validity.len() == 1 {
348            if validity.get_bit(0) {
349                Series(self.clone_inner())
350            } else {
351                Series::full_null(self._field().name().clone(), self.len(), self._dtype())
352            }
353        } else if self.len() == 1 && validity.len() != 1 {
354            self.new_from_index(0, validity.len()).mask(validity)
355        } else {
356            self.with_validity(combine_validities_and(
357                self.rechunk_validity().as_ref(),
358                Some(validity),
359            ))
360        }
361    }
362
363    /// Drop all null values and return a new Series.
364    fn drop_nulls(&self) -> Series {
365        if self.null_count() == 0 {
366            Series(self.clone_inner())
367        } else {
368            self.filter(&self.is_not_null()).unwrap()
369        }
370    }
371
372    /// Returns the sum of the array as an f64.
373    fn _sum_as_f64(&self) -> f64 {
374        invalid_operation_panic!(_sum_as_f64, self)
375    }
376
377    /// Returns the mean value in the array
378    /// Returns an option because the array is nullable.
379    fn mean(&self) -> Option<f64> {
380        None
381    }
382
383    /// Returns the std value in the array
384    /// Returns an option because the array is nullable.
385    fn std(&self, _ddof: u8) -> Option<f64> {
386        None
387    }
388
389    /// Returns the var value in the array
390    /// Returns an option because the array is nullable.
391    fn var(&self, _ddof: u8) -> Option<f64> {
392        None
393    }
394
395    /// Returns the median value in the array
396    /// Returns an option because the array is nullable.
397    fn median(&self) -> Option<f64> {
398        None
399    }
400
401    /// Create a new Series filled with values from the given index.
402    ///
403    /// # Example
404    ///
405    /// ```rust
406    /// use polars_core::prelude::*;
407    /// let s = Series::new("a".into(), [0i32, 1, 8]);
408    /// let s2 = s.new_from_index(2, 4);
409    /// assert_eq!(Vec::from(s2.i32().unwrap()), &[Some(8), Some(8), Some(8), Some(8)])
410    /// ```
411    fn new_from_index(&self, _index: usize, _length: usize) -> Series;
412
413    /// Trim all lists of unused start and end elements recursively.
414    ///
415    /// - `None` if nothing needed to be done.
416    /// - `Some(series)` if something changed.
417    fn trim_lists_to_normalized_offsets(&self) -> Option<Series> {
418        None
419    }
420
421    /// Propagate down nulls in nested types.
422    ///
423    /// - `None` if nothing needed to be done.
424    /// - `Some(series)` if something changed.
425    fn propagate_nulls(&self) -> Option<Series> {
426        None
427    }
428
429    fn deposit(&self, validity: &Bitmap) -> Series;
430
431    /// Find the indices of elements where the null masks are different recursively.
432    fn find_validity_mismatch(&self, other: &Series, idxs: &mut Vec<IdxSize>);
433
434    fn cast(&self, _dtype: &DataType, options: CastOptions) -> PolarsResult<Series>;
435
436    /// Get a single value by index. Don't use this operation for loops as a runtime cast is
437    /// needed for every iteration.
438    fn get(&self, index: usize) -> PolarsResult<AnyValue<'_>> {
439        polars_ensure!(index < self.len(), oob = index, self.len());
440        // SAFETY: Just did bounds check
441        let value = unsafe { self.get_unchecked(index) };
442        Ok(value)
443    }
444
445    /// Get a single value by index. Don't use this operation for loops as a runtime cast is
446    /// needed for every iteration.
447    ///
448    /// This may refer to physical types
449    ///
450    /// # Safety
451    /// Does not do any bounds checking
452    unsafe fn get_unchecked(&self, _index: usize) -> AnyValue<'_>;
453
454    fn sort_with(&self, _options: SortOptions) -> PolarsResult<Series> {
455        polars_bail!(opq = sort_with, self._dtype());
456    }
457
458    /// Retrieve the indexes needed for a sort.
459    #[allow(unused)]
460    fn arg_sort(&self, options: SortOptions) -> IdxCa {
461        invalid_operation_panic!(arg_sort, self)
462    }
463
464    /// Count the null values.
465    fn null_count(&self) -> usize;
466
467    /// Return if any the chunks in this [`ChunkedArray`] have nulls.
468    fn has_nulls(&self) -> bool;
469
470    /// Get unique values in the Series.
471    fn unique(&self) -> PolarsResult<Series> {
472        polars_bail!(opq = unique, self._dtype());
473    }
474
475    /// Get unique values in the Series.
476    ///
477    /// A `null` value also counts as a unique value.
478    fn n_unique(&self) -> PolarsResult<usize> {
479        polars_bail!(opq = n_unique, self._dtype());
480    }
481
482    /// Get first indexes of unique values.
483    fn arg_unique(&self) -> PolarsResult<IdxCa> {
484        polars_bail!(opq = arg_unique, self._dtype());
485    }
486
487    /// Get dense ids for each unique value.
488    ///
489    /// Returns: (n_unique, unique_ids)
490    fn unique_id(&self) -> PolarsResult<(IdxSize, Vec<IdxSize>)> {
491        polars_bail!(opq = unique_id, self._dtype());
492    }
493
494    /// Get a mask of the null values.
495    fn is_null(&self) -> BooleanChunked;
496
497    /// Get a mask of the non-null values.
498    fn is_not_null(&self) -> BooleanChunked;
499
500    /// return a Series in reversed order
501    fn reverse(&self) -> Series;
502
503    /// Rechunk and return a pointer to the start of the Series.
504    /// Only implemented for numeric types
505    fn as_single_ptr(&mut self) -> PolarsResult<usize> {
506        polars_bail!(opq = as_single_ptr, self._dtype());
507    }
508
509    /// Shift the values by a given period and fill the parts that will be empty due to this operation
510    /// with `Nones`.
511    ///
512    /// *NOTE: If you want to fill the Nones with a value use the
513    /// [`shift` operation on `ChunkedArray<T>`](../chunked_array/ops/trait.ChunkShift.html).*
514    ///
515    /// # Example
516    ///
517    /// ```rust
518    /// # use polars_core::prelude::*;
519    /// fn example() -> PolarsResult<()> {
520    ///     let s = Series::new("series".into(), &[1, 2, 3]);
521    ///
522    ///     let shifted = s.shift(1);
523    ///     assert_eq!(Vec::from(shifted.i32()?), &[None, Some(1), Some(2)]);
524    ///
525    ///     let shifted = s.shift(-1);
526    ///     assert_eq!(Vec::from(shifted.i32()?), &[Some(2), Some(3), None]);
527    ///
528    ///     let shifted = s.shift(2);
529    ///     assert_eq!(Vec::from(shifted.i32()?), &[None, None, Some(1)]);
530    ///
531    ///     Ok(())
532    /// }
533    /// example();
534    /// ```
535    fn shift(&self, _periods: i64) -> Series;
536
537    /// Get the sum of the Series as a new Scalar.
538    ///
539    /// If the [`DataType`] is one of `{Int8, UInt8, Int16, UInt16}` the `Series` is
540    /// first cast to `Int64` to prevent overflow issues.
541    fn sum_reduce(&self) -> PolarsResult<Scalar> {
542        polars_bail!(opq = sum, self._dtype());
543    }
544    /// Get the max of the Series as a new Series of length 1.
545    fn max_reduce(&self) -> PolarsResult<Scalar> {
546        polars_bail!(opq = max, self._dtype());
547    }
548    /// Get the min of the Series as a new Series of length 1.
549    fn min_reduce(&self) -> PolarsResult<Scalar> {
550        polars_bail!(opq = min, self._dtype());
551    }
552    /// Get the median of the Series as a new Series of length 1.
553    fn median_reduce(&self) -> PolarsResult<Scalar> {
554        polars_bail!(opq = median, self._dtype());
555    }
556    /// Get the mean of the Series as a new Scalar
557    fn mean_reduce(&self) -> PolarsResult<Scalar> {
558        polars_bail!(opq = mean, self._dtype());
559    }
560    /// Get the variance of the Series as a new Series of length 1.
561    fn var_reduce(&self, _ddof: u8) -> PolarsResult<Scalar> {
562        polars_bail!(opq = var, self._dtype());
563    }
564    /// Get the standard deviation of the Series as a new Series of length 1.
565    fn std_reduce(&self, _ddof: u8) -> PolarsResult<Scalar> {
566        polars_bail!(opq = std, self._dtype());
567    }
568    /// Get the quantile of the Series as a new Series of length 1.
569    fn quantile_reduce(&self, _quantile: f64, _method: QuantileMethod) -> PolarsResult<Scalar> {
570        polars_bail!(opq = quantile, self._dtype());
571    }
572    /// Get multiple quantiles of the ChunkedArray as a new `List` Scalar
573    fn quantiles_reduce(
574        &self,
575        _quantiles: &[f64],
576        _method: QuantileMethod,
577    ) -> PolarsResult<Scalar> {
578        polars_bail!(opq = quantiles, self._dtype());
579    }
580    /// Get the bitwise AND of the Series as a new Series of length 1,
581    fn and_reduce(&self) -> PolarsResult<Scalar> {
582        polars_bail!(opq = and_reduce, self._dtype());
583    }
584    /// Get the bitwise OR of the Series as a new Series of length 1,
585    fn or_reduce(&self) -> PolarsResult<Scalar> {
586        polars_bail!(opq = or_reduce, self._dtype());
587    }
588    /// Get the bitwise XOR of the Series as a new Series of length 1,
589    fn xor_reduce(&self) -> PolarsResult<Scalar> {
590        polars_bail!(opq = xor_reduce, self._dtype());
591    }
592
593    /// Get the first element of the [`Series`] as a [`Scalar`]
594    ///
595    /// If the [`Series`] is empty, a [`Scalar`] with a [`AnyValue::Null`] is returned.
596    fn first(&self) -> Scalar {
597        let dt = self.dtype();
598        let av = self.get(0).map_or(AnyValue::Null, AnyValue::into_static);
599
600        Scalar::new(dt.clone(), av)
601    }
602
603    /// Get the first non-null element of the [`Series`] as a [`Scalar`]
604    ///
605    /// If the [`Series`] is empty, a [`Scalar`] with a [`AnyValue::Null`] is returned.
606    fn first_non_null(&self) -> Scalar {
607        let av = if self.len() == 0 {
608            AnyValue::Null
609        } else {
610            let idx = if self.has_nulls() {
611                first_non_null(self.chunks().iter().map(|c| c.as_ref())).unwrap_or(0)
612            } else {
613                0
614            };
615            self.get(idx).map_or(AnyValue::Null, AnyValue::into_static)
616        };
617        Scalar::new(self.dtype().clone(), av)
618    }
619
620    /// Get the last element of the [`Series`] as a [`Scalar`]
621    ///
622    /// If the [`Series`] is empty, a [`Scalar`] with a [`AnyValue::Null`] is returned.
623    fn last(&self) -> Scalar {
624        let dt = self.dtype();
625        let av = if self.len() == 0 {
626            AnyValue::Null
627        } else {
628            // SAFETY: len-1 < len if len != 0
629            unsafe { self.get_unchecked(self.len() - 1) }.into_static()
630        };
631
632        Scalar::new(dt.clone(), av)
633    }
634
635    /// Get the last non-null element of the [`Series`] as a [`Scalar`]
636    ///
637    /// If the [`Series`] is empty, a [`Scalar`] with a [`AnyValue::Null`] is returned.
638    fn last_non_null(&self) -> Scalar {
639        let n = self.len();
640        let av = if n == 0 {
641            AnyValue::Null
642        } else {
643            let idx = if self.has_nulls() {
644                last_non_null(self.chunks().iter().map(|c| c.as_ref()), n).unwrap_or(n - 1)
645            } else {
646                n - 1
647            };
648            // SAFETY: len-1 < len if len != 0
649            unsafe { self.get_unchecked(idx) }.into_static()
650        };
651        Scalar::new(self.dtype().clone(), av)
652    }
653
654    #[cfg(feature = "approx_unique")]
655    fn approx_n_unique(&self) -> PolarsResult<IdxSize> {
656        polars_bail!(opq = approx_n_unique, self._dtype());
657    }
658
659    /// Clone inner ChunkedArray and wrap in a new Arc
660    fn clone_inner(&self) -> Arc<dyn SeriesTrait>;
661
662    #[cfg(feature = "object")]
663    /// Get the value at this index as a downcastable Any trait ref.
664    fn get_object(&self, _index: usize) -> Option<&dyn PolarsObjectSafe> {
665        invalid_operation_panic!(get_object, self)
666    }
667
668    #[cfg(feature = "object")]
669    /// Get the value at this index as a downcastable Any trait ref.
670    ///
671    /// # Safety
672    /// This function doesn't do any bound checks.
673    unsafe fn get_object_chunked_unchecked(
674        &self,
675        _chunk: usize,
676        _index: usize,
677    ) -> Option<&dyn PolarsObjectSafe> {
678        invalid_operation_panic!(get_object_chunked_unchecked, self)
679    }
680
681    /// Get a hold of the [`ChunkedArray`], [`Logical`] or `NullChunked` as an `Any` trait
682    /// reference.
683    fn as_any(&self) -> &dyn Any;
684
685    /// Get a hold of the [`ChunkedArray`], [`Logical`] or `NullChunked` as an `Any` trait mutable
686    /// reference.
687    fn as_any_mut(&mut self) -> &mut dyn Any;
688
689    /// Get a hold of the [`ChunkedArray`] or `NullChunked` as an `Any` trait reference. This
690    /// pierces through `Logical` types to get the underlying physical array.
691    fn as_phys_any(&self) -> &dyn Any;
692
693    fn as_arc_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
694
695    #[cfg(feature = "checked_arithmetic")]
696    fn checked_div(&self, _rhs: &Series) -> PolarsResult<Series> {
697        polars_bail!(opq = checked_div, self._dtype());
698    }
699
700    #[cfg(feature = "rolling_window")]
701    /// Apply a custom function over a rolling/ moving window of the array.
702    /// This has quite some dynamic dispatch, so prefer rolling_min, max, mean, sum over this.
703    fn rolling_map(
704        &self,
705        _f: &dyn Fn(&Series) -> PolarsResult<Series>,
706        _options: RollingOptionsFixedWindow,
707    ) -> PolarsResult<Series> {
708        polars_bail!(opq = rolling_map, self._dtype());
709    }
710}
711
712impl dyn SeriesTrait + '_ {
713    pub fn unpack<T: PolarsPhysicalType>(&self) -> PolarsResult<&ChunkedArray<T>> {
714        polars_ensure!(&T::get_static_dtype() == self.dtype(), unpack);
715        Ok(self.as_ref())
716    }
717}