polars_core/chunked_array/ops/
mod.rs

1//! Traits for miscellaneous operations on ChunkedArray
2use arrow::offset::OffsetsBuffer;
3use polars_compute::rolling::QuantileMethod;
4
5use crate::prelude::*;
6
7pub(crate) mod aggregate;
8pub(crate) mod any_value;
9pub(crate) mod append;
10mod apply;
11#[cfg(feature = "approx_unique")]
12mod approx_n_unique;
13pub mod arity;
14mod bit_repr;
15mod bits;
16#[cfg(feature = "bitwise")]
17mod bitwise_reduce;
18pub(crate) mod chunkops;
19pub(crate) mod compare_inner;
20#[cfg(feature = "dtype-decimal")]
21mod decimal;
22pub(crate) mod downcast;
23pub(crate) mod explode;
24mod explode_and_offsets;
25mod extend;
26pub mod fill_null;
27mod filter;
28pub mod float_sorted_arg_max;
29mod for_each;
30pub mod full;
31pub mod gather;
32mod nesting_utils;
33pub(crate) mod nulls;
34mod reverse;
35#[cfg(feature = "rolling_window")]
36pub(crate) mod rolling_window;
37pub mod row_encode;
38pub mod search_sorted;
39mod set;
40mod shift;
41pub mod sort;
42#[cfg(feature = "algorithm_group_by")]
43pub(crate) mod unique;
44#[cfg(feature = "zip_with")]
45pub mod zip;
46
47pub use chunkops::_set_check_length;
48pub use nesting_utils::ChunkNestingUtils;
49#[cfg(feature = "serde-lazy")]
50use serde::{Deserialize, Serialize};
51pub use sort::options::*;
52
53use crate::chunked_array::cast::CastOptions;
54use crate::series::{BitRepr, IsSorted};
55pub trait Reinterpret {
56    fn reinterpret_signed(&self) -> Series {
57        unimplemented!()
58    }
59
60    fn reinterpret_unsigned(&self) -> Series {
61        unimplemented!()
62    }
63}
64
65/// Transmute [`ChunkedArray`] to bit representation.
66/// This is useful in hashing context and reduces no.
67/// of compiled code paths.
68pub(crate) trait ToBitRepr {
69    fn to_bit_repr(&self) -> BitRepr;
70}
71
72pub trait ChunkAnyValue {
73    /// Get a single value. Beware this is slow.
74    /// If you need to use this slightly performant, cast Categorical to UInt32
75    ///
76    /// # Safety
77    /// Does not do any bounds checking.
78    unsafe fn get_any_value_unchecked(&self, index: usize) -> AnyValue<'_>;
79
80    /// Get a single value. Beware this is slow.
81    fn get_any_value(&self, index: usize) -> PolarsResult<AnyValue<'_>>;
82}
83
84pub trait ChunkAnyValueBypassValidity {
85    /// Get a single value bypassing the validity map. Beware this is slow.
86    ///
87    /// # Safety
88    /// Does not do any bounds checking.
89    unsafe fn get_any_value_bypass_validity(&self, index: usize) -> AnyValue<'_>;
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
93#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
94#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
95pub struct ExplodeOptions {
96    /// Explode an empty list into a `null`.
97    pub empty_as_null: bool,
98    /// Explode a `null` into a `null`.
99    pub keep_nulls: bool,
100}
101
102/// Explode/flatten a List or String Series
103pub trait ChunkExplode {
104    fn explode(&self, options: ExplodeOptions) -> PolarsResult<Series> {
105        self.explode_and_offsets(options).map(|t| t.0)
106    }
107    fn offsets(&self) -> PolarsResult<OffsetsBuffer<i64>>;
108    fn explode_and_offsets(
109        &self,
110        options: ExplodeOptions,
111    ) -> PolarsResult<(Series, OffsetsBuffer<i64>)>;
112}
113
114pub trait ChunkBytes {
115    fn to_byte_slices(&self) -> Vec<&[u8]>;
116}
117
118/// This differs from ChunkWindowCustom and ChunkWindow
119/// by not using a fold aggregator, but reusing a `Series` wrapper and calling `Series` aggregators.
120/// This likely is a bit slower than ChunkWindow
121#[cfg(feature = "rolling_window")]
122pub trait ChunkRollApply: AsRefDataType {
123    fn rolling_map(
124        &self,
125        f: &dyn Fn(&Series) -> PolarsResult<Series>,
126        options: RollingOptionsFixedWindow,
127    ) -> PolarsResult<Series>
128    where
129        Self: Sized;
130}
131
132pub trait ChunkTake<Idx: ?Sized>: ChunkTakeUnchecked<Idx> {
133    /// Gather values from ChunkedArray by index.
134    fn take(&self, indices: &Idx) -> PolarsResult<Self>
135    where
136        Self: Sized;
137}
138
139pub trait ChunkTakeUnchecked<Idx: ?Sized> {
140    /// Gather values from ChunkedArray by index.
141    ///
142    /// # Safety
143    /// The non-null indices must be valid.
144    unsafe fn take_unchecked(&self, indices: &Idx) -> Self;
145}
146
147/// Create a `ChunkedArray` with new values by index or by boolean mask.
148///
149/// Note that these operations clone data. This is however the only way we can modify at mask or
150/// index level as the underlying Arrow arrays are immutable.
151pub trait ChunkSet<'a, A, B> {
152    /// Set the values at indexes `idx` to some optional value `Option<T>`.
153    ///
154    /// # Example
155    ///
156    /// ```rust
157    /// # use polars_core::prelude::*;
158    /// let ca = UInt32Chunked::new("a".into(), &[1, 2, 3]);
159    /// let new = ca.scatter_single(vec![0, 1], Some(10)).unwrap();
160    ///
161    /// assert_eq!(Vec::from(&new), &[Some(10), Some(10), Some(3)]);
162    /// ```
163    fn scatter_single<I: IntoIterator<Item = IdxSize>>(
164        &'a self,
165        idx: I,
166        opt_value: Option<A>,
167    ) -> PolarsResult<Self>
168    where
169        Self: Sized;
170
171    /// Set the values at indexes `idx` by applying a closure to these values.
172    ///
173    /// # Example
174    ///
175    /// ```rust
176    /// # use polars_core::prelude::*;
177    /// let ca = Int32Chunked::new("a".into(), &[1, 2, 3]);
178    /// let new = ca.scatter_with(vec![0, 1], |opt_v| opt_v.map(|v| v - 5)).unwrap();
179    ///
180    /// assert_eq!(Vec::from(&new), &[Some(-4), Some(-3), Some(3)]);
181    /// ```
182    fn scatter_with<I: IntoIterator<Item = IdxSize>, F>(
183        &'a self,
184        idx: I,
185        f: F,
186    ) -> PolarsResult<Self>
187    where
188        Self: Sized,
189        F: Fn(Option<A>) -> Option<B>;
190    /// Set the values where the mask evaluates to `true` to some optional value `Option<T>`.
191    ///
192    /// # Example
193    ///
194    /// ```rust
195    /// # use polars_core::prelude::*;
196    /// let ca = Int32Chunked::new("a".into(), &[1, 2, 3]);
197    /// let mask = BooleanChunked::new("mask".into(), &[false, true, false]);
198    /// let new = ca.set(&mask, Some(5)).unwrap();
199    /// assert_eq!(Vec::from(&new), &[Some(1), Some(5), Some(3)]);
200    /// ```
201    fn set(&'a self, mask: &BooleanChunked, opt_value: Option<A>) -> PolarsResult<Self>
202    where
203        Self: Sized;
204}
205
206/// Cast `ChunkedArray<T>` to `ChunkedArray<N>`
207pub trait ChunkCast {
208    /// Cast a [`ChunkedArray`] to [`DataType`]
209    fn cast(&self, dtype: &DataType) -> PolarsResult<Series> {
210        self.cast_with_options(dtype, CastOptions::NonStrict)
211    }
212
213    /// Cast a [`ChunkedArray`] to [`DataType`]
214    fn cast_with_options(&self, dtype: &DataType, options: CastOptions) -> PolarsResult<Series>;
215
216    /// Does not check if the cast is a valid one and may over/underflow
217    ///
218    /// # Safety
219    /// - This doesn't do utf8 validation checking when casting from binary
220    /// - This doesn't do categorical bound checking when casting from UInt32
221    unsafe fn cast_unchecked(&self, dtype: &DataType) -> PolarsResult<Series>;
222}
223
224/// Fastest way to do elementwise operations on a [`ChunkedArray<T>`] when the operation is cheaper than
225/// branching due to null checking.
226pub trait ChunkApply<'a, T> {
227    type FuncRet;
228
229    /// Apply a closure elementwise. This is fastest when the null check branching is more expensive
230    /// than the closure application. Often it is.
231    ///
232    /// Null values remain null.
233    ///
234    /// # Example
235    ///
236    /// ```
237    /// use polars_core::prelude::*;
238    /// fn double(ca: &UInt32Chunked) -> UInt32Chunked {
239    ///     ca.apply_values(|v| v * 2)
240    /// }
241    /// ```
242    #[must_use]
243    fn apply_values<F>(&'a self, f: F) -> Self
244    where
245        F: Fn(T) -> Self::FuncRet + Copy;
246
247    /// Apply a closure elementwise including null values.
248    #[must_use]
249    fn apply<F>(&'a self, f: F) -> Self
250    where
251        F: Fn(Option<T>) -> Option<Self::FuncRet> + Copy;
252
253    /// Apply a closure elementwise and write results to a mutable slice.
254    fn apply_to_slice<F, S>(&'a self, f: F, slice: &mut [S])
255    // (value of chunkedarray, value of slice) -> value of slice
256    where
257        F: Fn(Option<T>, &S) -> S;
258}
259
260/// Aggregation operations.
261pub trait ChunkAgg<T> {
262    /// Aggregate the sum of the ChunkedArray.
263    /// Returns `None` if not implemented for `T`.
264    /// If the array is empty, `0` is returned
265    fn sum(&self) -> Option<T> {
266        None
267    }
268
269    fn _sum_as_f64(&self) -> f64;
270
271    fn min(&self) -> Option<T> {
272        None
273    }
274
275    /// Returns the maximum value in the array, according to the natural order.
276    /// Returns `None` if the array is empty or only contains null values.
277    fn max(&self) -> Option<T> {
278        None
279    }
280
281    fn min_max(&self) -> Option<(T, T)> {
282        Some((self.min()?, self.max()?))
283    }
284
285    /// Returns the mean value in the array.
286    /// Returns `None` if the array is empty or only contains null values.
287    fn mean(&self) -> Option<f64> {
288        None
289    }
290}
291
292/// Quantile and median aggregation.
293pub trait ChunkQuantile<T> {
294    /// Returns the mean value in the array.
295    /// Returns `None` if the array is empty or only contains null values.
296    fn median(&self) -> Option<T> {
297        None
298    }
299    /// Aggregate a given quantile of the ChunkedArray.
300    /// Returns `None` if the array is empty or only contains null values.
301    fn quantile(&self, _quantile: f64, _method: QuantileMethod) -> PolarsResult<Option<T>> {
302        Ok(None)
303    }
304}
305
306/// Variance and standard deviation aggregation.
307pub trait ChunkVar {
308    /// Compute the variance of this ChunkedArray/Series.
309    fn var(&self, _ddof: u8) -> Option<f64> {
310        None
311    }
312
313    /// Compute the standard deviation of this ChunkedArray/Series.
314    fn std(&self, _ddof: u8) -> Option<f64> {
315        None
316    }
317}
318
319/// Bitwise Reduction Operations.
320#[cfg(feature = "bitwise")]
321pub trait ChunkBitwiseReduce {
322    type Physical;
323
324    fn and_reduce(&self) -> Option<Self::Physical>;
325    fn or_reduce(&self) -> Option<Self::Physical>;
326    fn xor_reduce(&self) -> Option<Self::Physical>;
327}
328
329/// Compare [`Series`] and [`ChunkedArray`]'s and get a `boolean` mask that
330/// can be used to filter rows.
331///
332/// # Example
333///
334/// ```
335/// use polars_core::prelude::*;
336/// fn filter_all_ones(df: &DataFrame) -> PolarsResult<DataFrame> {
337///     let mask = df
338///     .column("column_a")?
339///     .as_materialized_series()
340///     .equal(1)?;
341///
342///     df.filter(&mask)
343/// }
344/// ```
345pub trait ChunkCompareEq<Rhs> {
346    type Item;
347
348    /// Check for equality.
349    fn equal(&self, rhs: Rhs) -> Self::Item;
350
351    /// Check for equality where `None == None`.
352    fn equal_missing(&self, rhs: Rhs) -> Self::Item;
353
354    /// Check for inequality.
355    fn not_equal(&self, rhs: Rhs) -> Self::Item;
356
357    /// Check for inequality where `None == None`.
358    fn not_equal_missing(&self, rhs: Rhs) -> Self::Item;
359}
360
361/// Compare [`Series`] and [`ChunkedArray`]'s using inequality operators (`<`, `>=`, etc.) and get
362/// a `boolean` mask that can be used to filter rows.
363pub trait ChunkCompareIneq<Rhs> {
364    type Item;
365
366    /// Greater than comparison.
367    fn gt(&self, rhs: Rhs) -> Self::Item;
368
369    /// Greater than or equal comparison.
370    fn gt_eq(&self, rhs: Rhs) -> Self::Item;
371
372    /// Less than comparison.
373    fn lt(&self, rhs: Rhs) -> Self::Item;
374
375    /// Less than or equal comparison
376    fn lt_eq(&self, rhs: Rhs) -> Self::Item;
377}
378
379/// Get unique values in a `ChunkedArray`
380pub trait ChunkUnique {
381    // We don't return Self to be able to use AutoRef specialization
382    /// Get unique values of a ChunkedArray
383    fn unique(&self) -> PolarsResult<Self>
384    where
385        Self: Sized;
386
387    /// Get first index of the unique values in a `ChunkedArray`.
388    /// This Vec is sorted.
389    fn arg_unique(&self) -> PolarsResult<IdxCa>;
390
391    /// Number of unique values in the `ChunkedArray`
392    fn n_unique(&self) -> PolarsResult<usize> {
393        self.arg_unique().map(|v| v.len())
394    }
395
396    /// Get dense ids for each unique value.
397    ///
398    /// Returns: (n_unique, unique_ids)
399    fn unique_id(&self) -> PolarsResult<(IdxSize, Vec<IdxSize>)>;
400}
401
402#[cfg(feature = "approx_unique")]
403pub trait ChunkApproxNUnique {
404    fn approx_n_unique(&self) -> IdxSize;
405}
406
407/// Sort operations on `ChunkedArray`.
408pub trait ChunkSort<T: PolarsDataType> {
409    #[allow(unused_variables)]
410    fn sort_with(&self, options: SortOptions) -> ChunkedArray<T>;
411
412    /// Returned a sorted `ChunkedArray`.
413    fn sort(&self, descending: bool) -> ChunkedArray<T>;
414
415    /// Retrieve the indexes needed to sort this array.
416    fn arg_sort(&self, options: SortOptions) -> IdxCa;
417
418    /// Retrieve the indexes need to sort this and the other arrays.
419    #[allow(unused_variables)]
420    fn arg_sort_multiple(
421        &self,
422        by: &[Column],
423        _options: &SortMultipleOptions,
424    ) -> PolarsResult<IdxCa> {
425        polars_bail!(opq = arg_sort_multiple, T::get_static_dtype());
426    }
427}
428
429pub type FillNullLimit = Option<IdxSize>;
430
431#[derive(Copy, Clone, Debug, PartialEq, Hash)]
432#[cfg_attr(feature = "serde-lazy", derive(Serialize, Deserialize))]
433#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
434pub enum FillNullStrategy {
435    /// previous value in array
436    Backward(FillNullLimit),
437    /// next value in array
438    Forward(FillNullLimit),
439    /// mean value of array
440    Mean,
441    /// minimal value in array
442    Min,
443    /// maximum value in array
444    Max,
445    /// replace with the value zero
446    Zero,
447    /// replace with the value one
448    One,
449}
450
451impl FillNullStrategy {
452    pub fn is_elementwise(&self) -> bool {
453        matches!(self, Self::One | Self::Zero)
454    }
455}
456
457/// Replace None values with a value
458pub trait ChunkFillNullValue<T> {
459    /// Replace None values with a give value `T`.
460    fn fill_null_with_values(&self, value: T) -> PolarsResult<Self>
461    where
462        Self: Sized;
463}
464
465/// Fill a ChunkedArray with one value.
466pub trait ChunkFull<T> {
467    /// Create a ChunkedArray with a single value.
468    fn full(name: PlSmallStr, value: T, length: usize) -> Self
469    where
470        Self: Sized;
471}
472
473pub trait ChunkFullNull {
474    fn full_null(_name: PlSmallStr, _length: usize) -> Self
475    where
476        Self: Sized;
477}
478
479/// Reverse a [`ChunkedArray<T>`]
480pub trait ChunkReverse {
481    /// Return a reversed version of this array.
482    fn reverse(&self) -> Self;
483}
484
485/// Filter values by a boolean mask.
486pub trait ChunkFilter<T: PolarsDataType> {
487    /// Filter values in the ChunkedArray with a boolean mask.
488    ///
489    /// ```rust
490    /// # use polars_core::prelude::*;
491    /// let array = Int32Chunked::new("array".into(), &[1, 2, 3]);
492    /// let mask = BooleanChunked::new("mask".into(), &[true, false, true]);
493    ///
494    /// let filtered = array.filter(&mask).unwrap();
495    /// assert_eq!(Vec::from(&filtered), [Some(1), Some(3)])
496    /// ```
497    fn filter(&self, filter: &BooleanChunked) -> PolarsResult<ChunkedArray<T>>
498    where
499        Self: Sized;
500}
501
502/// Create a new ChunkedArray filled with values at that index.
503pub trait ChunkExpandAtIndex<T: PolarsDataType> {
504    /// Create a new ChunkedArray filled with values at that index.
505    fn new_from_index(&self, index: usize, length: usize) -> ChunkedArray<T>;
506}
507
508macro_rules! impl_chunk_expand {
509    ($self:ident, $length:ident, $index:ident) => {{
510        if $self.is_empty() {
511            return $self.clone();
512        }
513        let opt_val = $self.get($index);
514        match opt_val {
515            Some(val) => ChunkedArray::full($self.name().clone(), val, $length),
516            None => ChunkedArray::full_null($self.name().clone(), $length),
517        }
518    }};
519}
520
521impl<T: PolarsNumericType> ChunkExpandAtIndex<T> for ChunkedArray<T>
522where
523    ChunkedArray<T>: ChunkFull<T::Native>,
524{
525    fn new_from_index(&self, index: usize, length: usize) -> ChunkedArray<T> {
526        let mut out = impl_chunk_expand!(self, length, index);
527        out.set_sorted_flag(IsSorted::Ascending);
528        out
529    }
530}
531
532impl ChunkExpandAtIndex<BooleanType> for BooleanChunked {
533    fn new_from_index(&self, index: usize, length: usize) -> BooleanChunked {
534        let mut out = impl_chunk_expand!(self, length, index);
535        out.set_sorted_flag(IsSorted::Ascending);
536        out
537    }
538}
539
540impl ChunkExpandAtIndex<StringType> for StringChunked {
541    fn new_from_index(&self, index: usize, length: usize) -> StringChunked {
542        let mut out = impl_chunk_expand!(self, length, index);
543        out.set_sorted_flag(IsSorted::Ascending);
544        out
545    }
546}
547
548impl ChunkExpandAtIndex<BinaryType> for BinaryChunked {
549    fn new_from_index(&self, index: usize, length: usize) -> BinaryChunked {
550        let mut out = impl_chunk_expand!(self, length, index);
551        out.set_sorted_flag(IsSorted::Ascending);
552        out
553    }
554}
555
556impl ChunkExpandAtIndex<BinaryOffsetType> for BinaryOffsetChunked {
557    fn new_from_index(&self, index: usize, length: usize) -> BinaryOffsetChunked {
558        let mut out = impl_chunk_expand!(self, length, index);
559        out.set_sorted_flag(IsSorted::Ascending);
560        out
561    }
562}
563
564impl ChunkExpandAtIndex<ListType> for ListChunked {
565    fn new_from_index(&self, index: usize, length: usize) -> ListChunked {
566        let opt_val = self.get_as_series(index);
567        match opt_val {
568            Some(val) => {
569                let mut ca = ListChunked::full(self.name().clone(), &val, length);
570                unsafe { ca.to_logical(self.inner_dtype().clone()) };
571                ca
572            },
573            None => {
574                ListChunked::full_null_with_dtype(self.name().clone(), length, self.inner_dtype())
575            },
576        }
577    }
578}
579
580#[cfg(feature = "dtype-struct")]
581impl ChunkExpandAtIndex<StructType> for StructChunked {
582    fn new_from_index(&self, index: usize, length: usize) -> ChunkedArray<StructType> {
583        let (chunk_idx, idx) = self.index_to_chunked_index(index);
584        let chunk = self.downcast_chunks().get(chunk_idx).unwrap();
585        let chunk = if chunk.is_null(idx) {
586            new_null_array(chunk.dtype().clone(), length)
587        } else {
588            let values = chunk
589                .values()
590                .iter()
591                .map(|arr| {
592                    let s = Series::try_from((PlSmallStr::EMPTY, arr.clone())).unwrap();
593                    let s = s.new_from_index(idx, length);
594                    s.chunks()[0].clone()
595                })
596                .collect::<Vec<_>>();
597
598            StructArray::new(chunk.dtype().clone(), length, values, None).boxed()
599        };
600
601        // SAFETY: chunks are from self.
602        unsafe { self.copy_with_chunks(vec![chunk]) }
603    }
604}
605
606#[cfg(feature = "dtype-array")]
607impl ChunkExpandAtIndex<FixedSizeListType> for ArrayChunked {
608    fn new_from_index(&self, index: usize, length: usize) -> ArrayChunked {
609        let opt_val = self.get_as_series(index);
610        match opt_val {
611            Some(val) => {
612                let mut ca = ArrayChunked::full(self.name().clone(), &val, length);
613                unsafe { ca.to_logical(self.inner_dtype().clone()) };
614                ca
615            },
616            None => ArrayChunked::full_null_with_dtype(
617                self.name().clone(),
618                length,
619                self.inner_dtype(),
620                self.width(),
621            ),
622        }
623    }
624}
625
626#[cfg(feature = "object")]
627impl<T: PolarsObject> ChunkExpandAtIndex<ObjectType<T>> for ObjectChunked<T> {
628    fn new_from_index(&self, index: usize, length: usize) -> ObjectChunked<T> {
629        let opt_val = self.get(index);
630        match opt_val {
631            Some(val) => ObjectChunked::<T>::full(self.name().clone(), val.clone(), length),
632            None => ObjectChunked::<T>::full_null(self.name().clone(), length),
633        }
634    }
635}
636
637/// Shift the values of a [`ChunkedArray`] by a number of periods.
638pub trait ChunkShiftFill<T: PolarsDataType, V> {
639    /// Shift the values by a given period and fill the parts that will be empty due to this operation
640    /// with `fill_value`.
641    fn shift_and_fill(&self, periods: i64, fill_value: V) -> ChunkedArray<T>;
642}
643
644pub trait ChunkShift<T: PolarsDataType> {
645    fn shift(&self, periods: i64) -> ChunkedArray<T>;
646}
647
648/// Combine two [`ChunkedArray`] based on some predicate.
649pub trait ChunkZip<T: PolarsDataType> {
650    /// Create a new ChunkedArray with values from self where the mask evaluates `true` and values
651    /// from `other` where the mask evaluates `false`
652    fn zip_with(
653        &self,
654        mask: &BooleanChunked,
655        other: &ChunkedArray<T>,
656    ) -> PolarsResult<ChunkedArray<T>>;
657}
658
659/// Apply kernels on the arrow array chunks in a ChunkedArray.
660pub trait ChunkApplyKernel<A: Array> {
661    /// Apply kernel and return result as a new ChunkedArray.
662    #[must_use]
663    fn apply_kernel(&self, f: &dyn Fn(&A) -> ArrayRef) -> Self;
664
665    /// Apply a kernel that outputs an array of different type.
666    fn apply_kernel_cast<S>(&self, f: &dyn Fn(&A) -> ArrayRef) -> ChunkedArray<S>
667    where
668        S: PolarsDataType;
669}
670
671#[cfg(feature = "is_first_distinct")]
672/// Mask the first unique values as `true`
673pub trait IsFirstDistinct<T: PolarsDataType> {
674    fn is_first_distinct(&self) -> PolarsResult<BooleanChunked> {
675        polars_bail!(opq = is_first_distinct, T::get_static_dtype());
676    }
677}
678
679#[cfg(feature = "is_last_distinct")]
680/// Mask the last unique values as `true`
681pub trait IsLastDistinct<T: PolarsDataType> {
682    fn is_last_distinct(&self) -> PolarsResult<BooleanChunked> {
683        polars_bail!(opq = is_last_distinct, T::get_static_dtype());
684    }
685}