Skip to main content

polars_core/frame/column/
mod.rs

1use std::borrow::Cow;
2
3pub use dictionary::{DictionaryColumn, SharedDictionary, dictionary_codes_enabled};
4use num_traits::{Num, NumCast};
5use polars_arrow::bitmap::{Bitmap, BitmapBuilder};
6use polars_arrow::trusted_len::TrustMyLength;
7use polars_compute::rolling::QuantileMethod;
8use polars_error::{PolarsContext, PolarsResult};
9use polars_utils::aliases::PlSeedableRandomStateQuality;
10use polars_utils::broadcast::{BroadcastLength, broadcast_len};
11use polars_utils::index::check_bounds;
12use polars_utils::pl_str::PlSmallStr;
13use polars_utils::slice_enum::Slice;
14pub use scalar::ScalarColumn;
15
16use self::compare_inner::TotalOrdInner;
17use self::gather::check_bounds_ca;
18use self::series::SeriesColumn;
19use crate::chunked_array::cast::CastOptions;
20use crate::chunked_array::flags::StatisticsFlags;
21use crate::datatypes::ReshapeDimension;
22#[cfg(feature = "algorithm_group_by")]
23use crate::frame::group_by::aggregations::nulls_at_one_end;
24use crate::prelude::*;
25use crate::series::{BitRepr, IsSorted};
26use crate::utils::Container;
27use crate::{HEAD_DEFAULT_LENGTH, TAIL_DEFAULT_LENGTH};
28
29mod arithmetic;
30mod compare;
31mod dictionary;
32mod scalar;
33mod series;
34
35/// A column within a [`DataFrame`].
36///
37/// This is lazily initialized to a [`Series`] with methods like
38/// [`as_materialized_series`][Column::as_materialized_series] and
39/// [`take_materialized_series`][Column::take_materialized_series].
40///
41/// Currently, there are three ways to represent a [`Column`].
42/// 1. A [`Series`] of values
43/// 2. A [`ScalarColumn`] that repeats a single [`Scalar`]
44/// 3. A [`DictionaryColumn`] of String codes into a shared dictionary
45#[derive(Debug, Clone)]
46#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
47#[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
48pub enum Column {
49    Series(SeriesColumn),
50    Scalar(ScalarColumn),
51    /// Serialized as a [`Column::Series`] of its values, so the format is unchanged.
52    #[cfg_attr(feature = "serde", serde(skip))]
53    #[cfg_attr(feature = "dsl-schema", schemars(skip))]
54    Dictionary(DictionaryColumn),
55}
56
57#[cfg(feature = "serde")]
58impl serde::Serialize for Column {
59    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
60        #[derive(serde::Serialize)]
61        #[serde(rename = "Column")]
62        enum Repr<'a> {
63            Series(Cow<'a, SeriesColumn>),
64            Scalar(&'a ScalarColumn),
65        }
66        match self {
67            Column::Series(s) => Repr::Series(Cow::Borrowed(s)),
68            Column::Scalar(s) => Repr::Scalar(s),
69            Column::Dictionary(d) => Repr::Series(Cow::Owned(SeriesColumn::new(
70                d.as_materialized_series().clone(),
71            ))),
72        }
73        .serialize(serializer)
74    }
75}
76
77/// Convert `Self` into a [`Column`]
78pub trait IntoColumn: Sized {
79    fn into_column(self) -> Column;
80}
81
82impl Column {
83    #[inline]
84    #[track_caller]
85    pub fn new<T, Phantom>(name: PlSmallStr, values: T) -> Self
86    where
87        Phantom: ?Sized,
88        Series: NamedFrom<T, Phantom>,
89    {
90        Self::Series(SeriesColumn::new(NamedFrom::new(name, values)))
91    }
92
93    #[inline]
94    pub fn new_empty(name: PlSmallStr, dtype: &DataType) -> Self {
95        Self::new_scalar(name, Scalar::new(dtype.clone(), AnyValue::Null), 0)
96    }
97
98    #[inline]
99    pub fn new_scalar(name: PlSmallStr, scalar: Scalar, length: usize) -> Self {
100        Self::Scalar(ScalarColumn::new(name, scalar, length))
101    }
102
103    pub fn new_row_index(name: PlSmallStr, offset: IdxSize, length: usize) -> PolarsResult<Column> {
104        let Ok(length) = IdxSize::try_from(length) else {
105            polars_bail!(
106                ComputeError:
107                "row index length {} overflows IdxSize::MAX ({})",
108                length,
109                IdxSize::MAX,
110            )
111        };
112
113        if offset.checked_add(length).is_none() {
114            polars_bail!(
115                ComputeError:
116                "row index with offset {} overflows on dataframe with height {}",
117                offset, length
118            )
119        }
120
121        let range = offset..offset + length;
122
123        let mut ca = IdxCa::from_vec(name, range.collect());
124        ca.set_sorted_flag(IsSorted::Ascending);
125        let col = ca.into_series().into();
126
127        Ok(col)
128    }
129
130    // # Materialize
131    /// Get a reference to a [`Series`] for this [`Column`]
132    ///
133    /// This may need to materialize the [`Series`] on the first invocation for a specific column.
134    #[inline]
135    pub fn as_materialized_series(&self) -> &Series {
136        match self {
137            Column::Series(s) => s,
138            Column::Scalar(s) => s.as_materialized_series(),
139            Column::Dictionary(s) => s.as_materialized_series(),
140        }
141    }
142
143    /// If the memory repr of this Column is a scalar, a unit-length Series will
144    /// be returned.
145    #[inline]
146    pub fn as_materialized_series_maintain_scalar(&self) -> Series {
147        match self {
148            Column::Scalar(s) => s.as_single_value_series(),
149            v => v.as_materialized_series().clone(),
150        }
151    }
152
153    /// Returns the backing `Series` for the values of this column.
154    ///
155    /// * For `Column::Series` columns, simply returns the inner `Series`.
156    /// * For `Column::Scalar` columns, returns an empty or unit length series.
157    ///
158    /// # Note
159    /// This method is safe to use. However, care must be taken when operating on the returned
160    /// `Series` to ensure result correctness. E.g. It is suitable to perform elementwise operations
161    /// on it, however e.g. aggregations will return unspecified results.
162    pub fn _get_backing_series(&self) -> Series {
163        match self {
164            Column::Series(s) => (**s).clone(),
165            Column::Scalar(s) => s.as_single_value_series(),
166            Column::Dictionary(s) => s.as_materialized_series().clone(),
167        }
168    }
169
170    /// Constructs a new `Column` of the same variant as `self` from a backing `Series` representing
171    /// the values.
172    ///
173    /// # Panics
174    /// Panics if:
175    /// * `self` is `Column::Series` and the length of `new_s` does not match that of `self`.
176    /// * `self` is `Column::Scalar` and if either:
177    ///   * `self` is not empty and `new_s` is not of unit length.
178    ///   * `self` is empty and `new_s` is not empty.
179    pub fn _to_new_from_backing(&self, new_s: Series) -> Self {
180        match self {
181            Column::Series(_) | Column::Dictionary(_) => {
182                assert_eq!(new_s.len(), self.len());
183                Column::Series(SeriesColumn::new(new_s))
184            },
185            Column::Scalar(s) => {
186                assert_eq!(new_s.len(), s.as_single_value_series().len());
187                Column::Scalar(ScalarColumn::from_single_value_series(new_s, self.len()))
188            },
189        }
190    }
191
192    /// Turn [`Column`] into a [`Column::Series`].
193    ///
194    /// This may need to materialize the [`Series`] on the first invocation for a specific column.
195    #[inline]
196    pub fn into_materialized_series(&mut self) -> &mut Series {
197        match self {
198            Column::Series(s) => s,
199            Column::Scalar(s) => {
200                let series = std::mem::replace(
201                    s,
202                    ScalarColumn::new_empty(PlSmallStr::EMPTY, DataType::Null),
203                )
204                .take_materialized_series();
205                *self = Column::Series(series.into());
206                let Column::Series(s) = self else {
207                    unreachable!();
208                };
209                s
210            },
211            Column::Dictionary(s) => {
212                let series = s.clone().take_materialized_series();
213                *self = Column::Series(series.into());
214                let Column::Series(s) = self else {
215                    unreachable!();
216                };
217                s
218            },
219        }
220    }
221    /// Take [`Series`] from a [`Column`]
222    ///
223    /// This may need to materialize the [`Series`] on the first invocation for a specific column.
224    #[inline]
225    pub fn take_materialized_series(self) -> Series {
226        match self {
227            Column::Series(s) => s.take(),
228            Column::Scalar(s) => s.take_materialized_series(),
229            Column::Dictionary(s) => s.take_materialized_series(),
230        }
231    }
232
233    #[inline]
234    pub fn dtype(&self) -> &DataType {
235        match self {
236            Column::Series(s) => s.dtype(),
237            Column::Scalar(s) => s.dtype(),
238            Column::Dictionary(s) => s.dtype(),
239        }
240    }
241
242    #[inline]
243    pub fn field(&self) -> Cow<'_, Field> {
244        match self {
245            Column::Series(s) => s.field(),
246            Column::Scalar(s) => match s.lazy_as_materialized_series() {
247                None => Cow::Owned(Field::new(s.name().clone(), s.dtype().clone())),
248                Some(s) => s.field(),
249            },
250            Column::Dictionary(s) => Cow::Owned(Field::new(s.name().clone(), DataType::String)),
251        }
252    }
253
254    #[inline]
255    pub fn name(&self) -> &PlSmallStr {
256        match self {
257            Column::Series(s) => s.name(),
258            Column::Scalar(s) => s.name(),
259            Column::Dictionary(s) => s.name(),
260        }
261    }
262
263    #[inline]
264    pub fn len(&self) -> usize {
265        match self {
266            Column::Series(s) => s.len(),
267            Column::Scalar(s) => s.len(),
268            Column::Dictionary(s) => s.len(),
269        }
270    }
271
272    #[inline]
273    pub fn with_name(mut self, name: PlSmallStr) -> Column {
274        self.rename(name);
275        self
276    }
277
278    #[inline]
279    pub fn rename(&mut self, name: PlSmallStr) {
280        match self {
281            Column::Series(s) => _ = s.rename(name),
282            Column::Scalar(s) => _ = s.rename(name),
283            Column::Dictionary(s) => s.rename(name),
284        }
285    }
286
287    // # Downcasting
288    #[inline]
289    pub fn as_series(&self) -> Option<&Series> {
290        match self {
291            Column::Series(s) => Some(s),
292            _ => None,
293        }
294    }
295
296    #[inline]
297    pub fn as_scalar_column(&self) -> Option<&ScalarColumn> {
298        match self {
299            Column::Scalar(s) => Some(s),
300            _ => None,
301        }
302    }
303    #[inline]
304    pub fn as_scalar_column_mut(&mut self) -> Option<&mut ScalarColumn> {
305        match self {
306            Column::Scalar(s) => Some(s),
307            _ => None,
308        }
309    }
310    #[inline]
311    pub fn as_dictionary_column(&self) -> Option<&DictionaryColumn> {
312        match self {
313            Column::Dictionary(s) => Some(s),
314            _ => None,
315        }
316    }
317
318    // # Try to Chunked Arrays
319    pub fn try_bool(&self) -> Option<&BooleanChunked> {
320        self.as_materialized_series().try_bool()
321    }
322    pub fn try_i8(&self) -> Option<&Int8Chunked> {
323        self.as_materialized_series().try_i8()
324    }
325    pub fn try_i16(&self) -> Option<&Int16Chunked> {
326        self.as_materialized_series().try_i16()
327    }
328    pub fn try_i32(&self) -> Option<&Int32Chunked> {
329        self.as_materialized_series().try_i32()
330    }
331    pub fn try_i64(&self) -> Option<&Int64Chunked> {
332        self.as_materialized_series().try_i64()
333    }
334    pub fn try_u8(&self) -> Option<&UInt8Chunked> {
335        self.as_materialized_series().try_u8()
336    }
337    pub fn try_u16(&self) -> Option<&UInt16Chunked> {
338        self.as_materialized_series().try_u16()
339    }
340    pub fn try_u32(&self) -> Option<&UInt32Chunked> {
341        self.as_materialized_series().try_u32()
342    }
343    pub fn try_u64(&self) -> Option<&UInt64Chunked> {
344        self.as_materialized_series().try_u64()
345    }
346    #[cfg(feature = "dtype-u128")]
347    pub fn try_u128(&self) -> Option<&UInt128Chunked> {
348        self.as_materialized_series().try_u128()
349    }
350    #[cfg(feature = "dtype-f16")]
351    pub fn try_f16(&self) -> Option<&Float16Chunked> {
352        self.as_materialized_series().try_f16()
353    }
354    pub fn try_f32(&self) -> Option<&Float32Chunked> {
355        self.as_materialized_series().try_f32()
356    }
357    pub fn try_f64(&self) -> Option<&Float64Chunked> {
358        self.as_materialized_series().try_f64()
359    }
360    pub fn try_str(&self) -> Option<&StringChunked> {
361        self.as_materialized_series().try_str()
362    }
363    pub fn try_list(&self) -> Option<&ListChunked> {
364        self.as_materialized_series().try_list()
365    }
366    pub fn try_binary(&self) -> Option<&BinaryChunked> {
367        self.as_materialized_series().try_binary()
368    }
369    pub fn try_idx(&self) -> Option<&IdxCa> {
370        self.as_materialized_series().try_idx()
371    }
372    pub fn try_binary_offset(&self) -> Option<&BinaryOffsetChunked> {
373        self.as_materialized_series().try_binary_offset()
374    }
375    #[cfg(feature = "dtype-datetime")]
376    pub fn try_datetime(&self) -> Option<&DatetimeChunked> {
377        self.as_materialized_series().try_datetime()
378    }
379    #[cfg(feature = "dtype-struct")]
380    pub fn try_struct(&self) -> Option<&StructChunked> {
381        self.as_materialized_series().try_struct()
382    }
383    #[cfg(feature = "dtype-decimal")]
384    pub fn try_decimal(&self) -> Option<&DecimalChunked> {
385        self.as_materialized_series().try_decimal()
386    }
387    #[cfg(feature = "dtype-array")]
388    pub fn try_array(&self) -> Option<&ArrayChunked> {
389        self.as_materialized_series().try_array()
390    }
391    #[cfg(feature = "dtype-categorical")]
392    pub fn try_cat<T: PolarsCategoricalType>(&self) -> Option<&CategoricalChunked<T>> {
393        self.as_materialized_series().try_cat::<T>()
394    }
395    #[cfg(feature = "dtype-categorical")]
396    pub fn try_cat8(&self) -> Option<&Categorical8Chunked> {
397        self.as_materialized_series().try_cat8()
398    }
399    #[cfg(feature = "dtype-categorical")]
400    pub fn try_cat16(&self) -> Option<&Categorical16Chunked> {
401        self.as_materialized_series().try_cat16()
402    }
403    #[cfg(feature = "dtype-categorical")]
404    pub fn try_cat32(&self) -> Option<&Categorical32Chunked> {
405        self.as_materialized_series().try_cat32()
406    }
407    #[cfg(feature = "dtype-date")]
408    pub fn try_date(&self) -> Option<&DateChunked> {
409        self.as_materialized_series().try_date()
410    }
411    #[cfg(feature = "dtype-duration")]
412    pub fn try_duration(&self) -> Option<&DurationChunked> {
413        self.as_materialized_series().try_duration()
414    }
415
416    // # To Chunked Arrays
417    pub fn bool(&self) -> PolarsResult<&BooleanChunked> {
418        self.as_materialized_series().bool()
419    }
420    pub fn i8(&self) -> PolarsResult<&Int8Chunked> {
421        self.as_materialized_series().i8()
422    }
423    pub fn i16(&self) -> PolarsResult<&Int16Chunked> {
424        self.as_materialized_series().i16()
425    }
426    pub fn i32(&self) -> PolarsResult<&Int32Chunked> {
427        self.as_materialized_series().i32()
428    }
429    pub fn i64(&self) -> PolarsResult<&Int64Chunked> {
430        self.as_materialized_series().i64()
431    }
432    #[cfg(feature = "dtype-i128")]
433    pub fn i128(&self) -> PolarsResult<&Int128Chunked> {
434        self.as_materialized_series().i128()
435    }
436    pub fn u8(&self) -> PolarsResult<&UInt8Chunked> {
437        self.as_materialized_series().u8()
438    }
439    pub fn u16(&self) -> PolarsResult<&UInt16Chunked> {
440        self.as_materialized_series().u16()
441    }
442    pub fn u32(&self) -> PolarsResult<&UInt32Chunked> {
443        self.as_materialized_series().u32()
444    }
445    pub fn u64(&self) -> PolarsResult<&UInt64Chunked> {
446        self.as_materialized_series().u64()
447    }
448    #[cfg(feature = "dtype-u128")]
449    pub fn u128(&self) -> PolarsResult<&UInt128Chunked> {
450        self.as_materialized_series().u128()
451    }
452    #[cfg(feature = "dtype-f16")]
453    pub fn f16(&self) -> PolarsResult<&Float16Chunked> {
454        self.as_materialized_series().f16()
455    }
456    pub fn f32(&self) -> PolarsResult<&Float32Chunked> {
457        self.as_materialized_series().f32()
458    }
459    pub fn f64(&self) -> PolarsResult<&Float64Chunked> {
460        self.as_materialized_series().f64()
461    }
462    pub fn str(&self) -> PolarsResult<&StringChunked> {
463        self.as_materialized_series().str()
464    }
465    pub fn list(&self) -> PolarsResult<&ListChunked> {
466        self.as_materialized_series().list()
467    }
468    pub fn binary(&self) -> PolarsResult<&BinaryChunked> {
469        self.as_materialized_series().binary()
470    }
471    pub fn idx(&self) -> PolarsResult<&IdxCa> {
472        self.as_materialized_series().idx()
473    }
474    pub fn binary_offset(&self) -> PolarsResult<&BinaryOffsetChunked> {
475        self.as_materialized_series().binary_offset()
476    }
477    #[cfg(feature = "dtype-datetime")]
478    pub fn datetime(&self) -> PolarsResult<&DatetimeChunked> {
479        self.as_materialized_series().datetime()
480    }
481    #[cfg(feature = "dtype-struct")]
482    pub fn struct_(&self) -> PolarsResult<&StructChunked> {
483        self.as_materialized_series().struct_()
484    }
485    #[cfg(feature = "dtype-decimal")]
486    pub fn decimal(&self) -> PolarsResult<&DecimalChunked> {
487        self.as_materialized_series().decimal()
488    }
489    #[cfg(feature = "dtype-array")]
490    pub fn array(&self) -> PolarsResult<&ArrayChunked> {
491        self.as_materialized_series().array()
492    }
493    #[cfg(feature = "dtype-categorical")]
494    pub fn cat<T: PolarsCategoricalType>(&self) -> PolarsResult<&CategoricalChunked<T>> {
495        self.as_materialized_series().cat::<T>()
496    }
497    #[cfg(feature = "dtype-categorical")]
498    pub fn cat8(&self) -> PolarsResult<&Categorical8Chunked> {
499        self.as_materialized_series().cat8()
500    }
501    #[cfg(feature = "dtype-categorical")]
502    pub fn cat16(&self) -> PolarsResult<&Categorical16Chunked> {
503        self.as_materialized_series().cat16()
504    }
505    #[cfg(feature = "dtype-categorical")]
506    pub fn cat32(&self) -> PolarsResult<&Categorical32Chunked> {
507        self.as_materialized_series().cat32()
508    }
509    #[cfg(feature = "dtype-date")]
510    pub fn date(&self) -> PolarsResult<&DateChunked> {
511        self.as_materialized_series().date()
512    }
513    #[cfg(feature = "dtype-duration")]
514    pub fn duration(&self) -> PolarsResult<&DurationChunked> {
515        self.as_materialized_series().duration()
516    }
517
518    /// Strict cast of a dictionary column: casts the used values without failing, and only when
519    /// that nulls a value (or errors) casts the rows strictly, so that the error counts failing
520    /// rows, not distinct values.
521    fn strict_cast_dictionary(&self, d: &DictionaryColumn, dtype: &DataType) -> PolarsResult<Self> {
522        // Nested targets null fields inside a valid outer value, which the outer null count
523        // cannot see: always cast the rows strictly.
524        if dtype.is_nested() {
525            return self
526                .as_materialized_series()
527                .strict_cast(dtype)
528                .map(Column::from);
529        }
530        let out = d.apply_elementwise(|s| s.cast_with_options(dtype, CastOptions::NonStrict));
531        match out {
532            Ok(out) if out.null_count() == d.null_count() => Ok(out),
533            _ => self
534                .as_materialized_series()
535                .strict_cast(dtype)
536                .map(Column::from),
537        }
538    }
539
540    // # Casting
541    pub fn cast_with_options(&self, dtype: &DataType, options: CastOptions) -> PolarsResult<Self> {
542        match self {
543            Column::Dictionary(_) if dtype == &DataType::String => Ok(self.clone()),
544            // Casts each used dictionary value once, e.g. into a Categorical.
545            Column::Dictionary(d) if matches!(options, CastOptions::Strict) => {
546                self.strict_cast_dictionary(d, dtype)
547            },
548            Column::Dictionary(d) => d.apply_elementwise(|s| s.cast_with_options(dtype, options)),
549            Column::Series(s) => s.cast_with_options(dtype, options).map(Column::from),
550            Column::Scalar(s) => s.cast_with_options(dtype, options).map(Column::from),
551        }
552    }
553    pub fn strict_cast(&self, dtype: &DataType) -> PolarsResult<Self> {
554        match self {
555            Column::Dictionary(_) if dtype == &DataType::String => Ok(self.clone()),
556            // Casts each used dictionary value once, e.g. into a Categorical.
557            Column::Dictionary(d) => self.strict_cast_dictionary(d, dtype),
558            Column::Series(s) => s.strict_cast(dtype).map(Column::from),
559            Column::Scalar(s) => s.strict_cast(dtype).map(Column::from),
560        }
561    }
562    pub fn cast(&self, dtype: &DataType) -> PolarsResult<Column> {
563        match self {
564            Column::Dictionary(_) if dtype == &DataType::String => Ok(self.clone()),
565            // Casts each used dictionary value once, e.g. into a Categorical.
566            Column::Dictionary(d) => d.apply_elementwise(|s| s.cast(dtype)),
567            Column::Series(s) => s.cast(dtype).map(Column::from),
568            Column::Scalar(s) => s.cast(dtype).map(Column::from),
569        }
570    }
571    /// # Safety
572    ///
573    /// This can lead to invalid memory access in downstream code.
574    pub unsafe fn cast_unchecked(&self, dtype: &DataType) -> PolarsResult<Column> {
575        match self {
576            Column::Dictionary(_) if dtype == &DataType::String => Ok(self.clone()),
577            // Casts each used dictionary value once, e.g. into a Categorical.
578            Column::Dictionary(d) => d.apply_elementwise(|s| unsafe { s.cast_unchecked(dtype) }),
579            Column::Series(s) => unsafe { s.cast_unchecked(dtype) }.map(Column::from),
580            Column::Scalar(s) => unsafe { s.cast_unchecked(dtype) }.map(Column::from),
581        }
582    }
583
584    #[must_use]
585    pub fn clear(&self) -> Self {
586        match self {
587            Column::Series(s) => s.clear().into(),
588            Column::Scalar(s) => s.resize(0).into(),
589            Column::Dictionary(s) => DictionaryColumn::new_empty(s.name().clone()).into_column(),
590        }
591    }
592
593    #[inline]
594    pub fn shrink_to_fit(&mut self) {
595        match self {
596            Column::Series(s) => s.shrink_to_fit(),
597            Column::Scalar(_) | Column::Dictionary(_) => {},
598        }
599    }
600
601    #[inline]
602    pub fn new_from_index(&self, index: usize, length: usize) -> Self {
603        if index >= self.len() {
604            return Self::full_null(self.name().clone(), length, self.dtype());
605        }
606
607        match self {
608            Column::Series(_) | Column::Dictionary(_) => {
609                // SAFETY: Bounds check done before. (A dictionary column reads its value by code,
610                // without materializing.)
611                let av = unsafe { self.get_unchecked(index) };
612                let scalar = Scalar::new(self.dtype().clone(), av.into_static());
613                Self::new_scalar(self.name().clone(), scalar, length)
614            },
615            Column::Scalar(s) => s.resize(length).into(),
616        }
617    }
618
619    /// Returns a column with the given length.
620    ///
621    /// Errors if this column's length is not 1 and also not equal to the requested length.
622    pub fn broadcast_to(&self, length: usize) -> PolarsResult<Cow<'_, Self>> {
623        let len = self.len();
624        if len == length {
625            Ok(Cow::Borrowed(self))
626        } else if len == 1 {
627            Ok(Cow::Owned(self.new_from_index(0, length)))
628        } else {
629            polars_bail!(
630                ShapeMismatch: "can't broadcast Series '{}' of length {len} to length {length}",
631                self.name()
632            );
633        }
634    }
635
636    /// See broadcast_to.
637    pub fn broadcast_in_place_to(&mut self, length: usize) -> PolarsResult<()> {
638        if let Cow::Owned(new) = self.broadcast_to(length)? {
639            *self = new;
640        }
641        Ok(())
642    }
643
644    /// See broadcast_to.
645    pub fn broadcast_owned_to(mut self, length: usize) -> PolarsResult<Self> {
646        self.broadcast_in_place_to(length)?;
647        Ok(self)
648    }
649
650    #[inline]
651    pub fn has_nulls(&self) -> bool {
652        match self {
653            Self::Series(s) => s.has_nulls(),
654            Self::Scalar(s) => s.has_nulls(),
655            Self::Dictionary(s) => s.has_nulls(),
656        }
657    }
658
659    #[inline]
660    pub fn is_null(&self) -> BooleanChunked {
661        match self {
662            Self::Series(s) => s.is_null(),
663            Self::Dictionary(s) => s.codes().is_null().with_name(s.name().clone()),
664            Self::Scalar(s) => {
665                BooleanChunked::full(s.name().clone(), s.scalar().is_null(), s.len())
666            },
667        }
668    }
669    #[inline]
670    pub fn is_not_null(&self) -> BooleanChunked {
671        match self {
672            Self::Series(s) => s.is_not_null(),
673            Self::Dictionary(s) => s.codes().is_not_null().with_name(s.name().clone()),
674            Self::Scalar(s) => {
675                BooleanChunked::full(s.name().clone(), !s.scalar().is_null(), s.len())
676            },
677        }
678    }
679
680    pub fn to_physical_repr(&self) -> Column {
681        // @scalar-opt
682        self.as_materialized_series()
683            .to_physical_repr()
684            .into_owned()
685            .into()
686    }
687    /// # Safety
688    ///
689    /// This can lead to invalid memory access in downstream code.
690    pub unsafe fn from_physical_unchecked(&self, dtype: &DataType) -> PolarsResult<Column> {
691        // @scalar-opt
692        self.as_materialized_series()
693            .from_physical_unchecked(dtype)
694            .map(Column::from)
695    }
696
697    pub fn head(&self, length: Option<usize>) -> Column {
698        self.slice(Slice::head(length.unwrap_or(HEAD_DEFAULT_LENGTH)))
699    }
700    pub fn tail(&self, length: Option<usize>) -> Column {
701        self.slice(Slice::tail(length.unwrap_or(TAIL_DEFAULT_LENGTH)))
702    }
703    pub fn slice(&self, slice: impl Into<Slice>) -> Column {
704        let slice = slice.into();
705        match self {
706            Column::Series(s) => s.slice(slice).into(),
707            Column::Scalar(s) => s.resize(slice.resolve(s.len()).len()).into(),
708            Column::Dictionary(s) => s.slice(slice).into(),
709        }
710    }
711
712    pub fn split_at(&self, offset: i64) -> (Column, Column) {
713        match self {
714            Column::Scalar(c) => {
715                let len = c.len();
716                let offset = if offset < 0 {
717                    let offset_abs = usize::try_from(offset.strict_abs())
718                        .expect("offset exceeds usize limits")
719                        .min(len);
720                    len - offset_abs
721                } else {
722                    usize::try_from(offset)
723                        .expect("offset exceeds usize limits")
724                        .min(len)
725                };
726                (
727                    Column::Scalar(c.resize(offset)),
728                    Column::Scalar(c.resize(len - offset)),
729                )
730            },
731            Column::Dictionary(_) => {
732                let split = Slice::resolve_offset(offset, self.len());
733                (
734                    self.slice(Slice::head(split)),
735                    self.slice((split, self.len() - split)),
736                )
737            },
738            Column::Series(_) => {
739                let (l, r) = self.as_materialized_series().split_at(offset);
740                (l.into(), r.into())
741            },
742        }
743    }
744
745    #[inline]
746    pub fn null_count(&self) -> usize {
747        match self {
748            Self::Series(s) => s.null_count(),
749            Self::Dictionary(s) => s.null_count(),
750            Self::Scalar(s) if s.scalar().is_null() => s.len(),
751            Self::Scalar(_) => 0,
752        }
753    }
754
755    pub fn first_non_null(&self) -> Option<usize> {
756        match self {
757            Self::Series(s) => crate::utils::first_non_null(s.chunks().iter().map(|a| a.as_ref())),
758            Self::Dictionary(s) => {
759                crate::utils::first_non_null(s.codes().chunks().iter().map(|a| a.as_ref()))
760            },
761            Self::Scalar(s) => (!s.scalar().is_null() && !s.is_empty()).then_some(0),
762        }
763    }
764
765    pub fn last_non_null(&self) -> Option<usize> {
766        match self {
767            Self::Series(s) => {
768                crate::utils::last_non_null(s.chunks().iter().map(|a| a.as_ref()), s.len())
769            },
770            Self::Dictionary(s) => {
771                crate::utils::last_non_null(s.codes().chunks().iter().map(|a| a.as_ref()), s.len())
772            },
773            Self::Scalar(s) => (!s.scalar().is_null() && !s.is_empty()).then(|| s.len() - 1),
774        }
775    }
776
777    pub fn take(&self, indices: &IdxCa) -> PolarsResult<Column> {
778        check_bounds_ca(indices, self.len() as IdxSize)?;
779        Ok(unsafe { self.take_unchecked(indices) })
780    }
781    pub fn take_slice(&self, indices: &[IdxSize]) -> PolarsResult<Column> {
782        check_bounds(indices, self.len() as IdxSize)?;
783        Ok(unsafe { self.take_slice_unchecked(indices) })
784    }
785    /// # Safety
786    ///
787    /// No bounds on the indexes are performed.
788    pub unsafe fn take_unchecked(&self, indices: &IdxCa) -> Column {
789        debug_assert!(check_bounds_ca(indices, self.len() as IdxSize).is_ok());
790
791        match self {
792            Self::Series(s) => unsafe { s.take_unchecked(indices) }.into(),
793            Self::Dictionary(s) => unsafe { s.take_unchecked(indices) }.into(),
794            Self::Scalar(s) => {
795                let idxs_length = indices.len();
796                let idxs_null_count = indices.null_count();
797
798                let scalar = ScalarColumn::from_single_value_series(
799                    s.as_single_value_series().take_unchecked(&IdxCa::new(
800                        indices.name().clone(),
801                        &[0][..s.len().min(1)],
802                    )),
803                    idxs_length,
804                );
805
806                // We need to make sure that null values in `idx` become null values in the result
807                if idxs_null_count == 0 || scalar.has_nulls() {
808                    scalar.into_column()
809                } else if idxs_null_count == idxs_length {
810                    scalar.into_nulls().into_column()
811                } else {
812                    let validity = indices.rechunk_validity();
813                    // Use dtype-aware validity updates so Struct fields see the nulls.
814                    let mut out = scalar.take_materialized_series().with_validity(validity);
815                    // Gather indices can insert nulls between equal values.
816                    out.set_sorted_flag(IsSorted::Not);
817                    out.into_column()
818                }
819            },
820        }
821    }
822    /// # Safety
823    ///
824    /// No bounds on the indexes are performed.
825    pub unsafe fn take_slice_unchecked(&self, indices: &[IdxSize]) -> Column {
826        debug_assert!(check_bounds(indices, self.len() as IdxSize).is_ok());
827
828        match self {
829            Self::Series(s) => unsafe { s.take_slice_unchecked(indices) }.into(),
830            Self::Dictionary(s) => unsafe { s.take_slice_unchecked(indices) }.into(),
831            Self::Scalar(s) => ScalarColumn::from_single_value_series(
832                s.as_single_value_series()
833                    .take_slice_unchecked(&[0][..s.len().min(1)]),
834                indices.len(),
835            )
836            .into(),
837        }
838    }
839
840    /// General implementation for aggregation where a non-missing scalar would map to itself.
841    #[inline(always)]
842    #[cfg(any(feature = "algorithm_group_by", feature = "bitwise"))]
843    fn agg_with_scalar_identity(
844        &self,
845        groups: &GroupsType,
846        series_agg: impl Fn(&Series, &GroupsType) -> Series,
847    ) -> Column {
848        match self {
849            Column::Series(_) | Column::Dictionary(_) => {
850                series_agg(self.as_materialized_series(), groups).into_column()
851            },
852            Column::Scalar(s) => {
853                if s.is_empty() {
854                    return series_agg(s.as_materialized_series(), groups).into_column();
855                }
856
857                // We utilize the aggregation on Series to see:
858                // 1. the output datatype of the aggregation
859                // 2. whether this aggregation is even defined
860                let series_aggregation = series_agg(
861                    &s.as_single_value_series(),
862                    // @NOTE: this group is always valid since s is non-empty.
863                    &GroupsType::new_slice(vec![[0, 1]], false, true),
864                );
865
866                // If the aggregation is not defined, just return all nulls.
867                if series_aggregation.has_nulls() {
868                    return Self::new_scalar(
869                        series_aggregation.name().clone(),
870                        Scalar::new(series_aggregation.dtype().clone(), AnyValue::Null),
871                        groups.len(),
872                    );
873                }
874
875                // Broadcast the single-group result: it already has the output dtype and value
876                // (e.g. `mean` changes int -> float, `arg_max` yields the index `0`).
877                let scalar_col =
878                    ScalarColumn::from_single_value_series(series_aggregation, groups.len());
879
880                let Some(first_empty_idx) = groups.iter().position(|g| g.is_empty()) else {
881                    // Fast path: no empty groups. keep the scalar intact.
882                    return scalar_col.into_column();
883                };
884
885                // All empty groups produce a *missing* or `null` value.
886                let mut validity = BitmapBuilder::with_capacity(groups.len());
887                validity.extend_constant(first_empty_idx, true);
888                // SAFETY: We trust the length of this iterator.
889                let iter = unsafe {
890                    TrustMyLength::new(
891                        groups.iter().skip(first_empty_idx).map(|g| !g.is_empty()),
892                        groups.len() - first_empty_idx,
893                    )
894                };
895                validity.extend_trusted_len_iter(iter);
896
897                // Use dtype-aware validity updates so Struct fields see the nulls.
898                let s = scalar_col.take_materialized_series().rechunk();
899                let mut out = s.with_validity(validity.into_opt_validity());
900                // The values are equal, so the result is sorted only if its nulls are at one end.
901                if !nulls_at_one_end(&out) {
902                    out.set_sorted_flag(IsSorted::Not);
903                }
904                out.into_column()
905            },
906        }
907    }
908
909    /// # Safety
910    ///
911    /// Does no bounds checks, groups must be correct.
912    #[cfg(feature = "algorithm_group_by")]
913    pub unsafe fn agg_min(&self, groups: &GroupsType) -> Self {
914        self.agg_with_scalar_identity(groups, |s, g| unsafe { s.agg_min(g) })
915    }
916
917    /// # Safety
918    ///
919    /// Does no bounds checks, groups must be correct.
920    #[cfg(feature = "algorithm_group_by")]
921    pub unsafe fn agg_max(&self, groups: &GroupsType) -> Self {
922        self.agg_with_scalar_identity(groups, |s, g| unsafe { s.agg_max(g) })
923    }
924
925    /// # Safety
926    ///
927    /// Does no bounds checks, groups must be correct.
928    #[cfg(feature = "algorithm_group_by")]
929    pub unsafe fn agg_mean(&self, groups: &GroupsType) -> Self {
930        self.agg_with_scalar_identity(groups, |s, g| unsafe { s.agg_mean(g) })
931    }
932
933    #[cfg(feature = "algorithm_group_by")]
934    fn scalar_agg_arg_min_max(sc: &ScalarColumn, groups: &GroupsType) -> Self {
935        let name = sc.name().clone();
936        if sc.is_empty() || sc.has_nulls() {
937            return Self::full_null(name, groups.len(), &IDX_DTYPE);
938        }
939
940        // Empty groups have no min or max.
941        if groups.iter().any(|g| g.is_empty()) {
942            return IdxCa::from_iter_options(
943                name,
944                groups.iter().map(|g| (!g.is_empty()).then_some(0)),
945            )
946            .into_column();
947        }
948
949        Self::new_scalar(name, Scalar::new_idxsize(0), groups.len())
950    }
951
952    /// # Safety
953    ///
954    /// Does no bounds checks, groups must be correct.
955    #[cfg(feature = "algorithm_group_by")]
956    pub unsafe fn agg_arg_min(&self, groups: &GroupsType) -> Self {
957        match self {
958            Column::Series(_) | Column::Dictionary(_) => unsafe {
959                Column::from(self.as_materialized_series().agg_arg_min(groups))
960            },
961            Column::Scalar(sc) => Self::scalar_agg_arg_min_max(sc, groups),
962        }
963    }
964
965    /// # Safety
966    ///
967    /// Does no bounds checks, groups must be correct.
968    #[cfg(feature = "algorithm_group_by")]
969    pub unsafe fn agg_arg_max(&self, groups: &GroupsType) -> Self {
970        match self {
971            Column::Series(_) | Column::Dictionary(_) => unsafe {
972                Column::from(self.as_materialized_series().agg_arg_max(groups))
973            },
974            Column::Scalar(sc) => Self::scalar_agg_arg_min_max(sc, groups),
975        }
976    }
977
978    /// # Safety
979    ///
980    /// Does no bounds checks, groups must be correct.
981    #[cfg(feature = "algorithm_group_by")]
982    pub unsafe fn agg_sum(&self, groups: &GroupsType) -> Self {
983        // @scalar-opt
984        unsafe { self.as_materialized_series().agg_sum(groups) }.into()
985    }
986
987    /// # Safety
988    ///
989    /// Does no bounds checks, groups must be correct.
990    #[cfg(feature = "algorithm_group_by")]
991    pub unsafe fn agg_first(&self, groups: &GroupsType) -> Self {
992        self.agg_with_scalar_identity(groups, |s, g| unsafe { s.agg_first(g) })
993    }
994
995    /// # Safety
996    ///
997    /// Does no bounds checks, groups must be correct.
998    #[cfg(feature = "algorithm_group_by")]
999    pub unsafe fn agg_first_non_null(&self, groups: &GroupsType) -> Self {
1000        self.agg_with_scalar_identity(groups, |s, g| unsafe { s.agg_first_non_null(g) })
1001    }
1002
1003    /// # Safety
1004    ///
1005    /// Does no bounds checks, groups must be correct.
1006    #[cfg(feature = "algorithm_group_by")]
1007    pub unsafe fn agg_last(&self, groups: &GroupsType) -> Self {
1008        self.agg_with_scalar_identity(groups, |s, g| unsafe { s.agg_last(g) })
1009    }
1010
1011    /// # Safety
1012    ///
1013    /// Does no bounds checks, groups must be correct.
1014    #[cfg(feature = "algorithm_group_by")]
1015    pub unsafe fn agg_last_non_null(&self, groups: &GroupsType) -> Self {
1016        self.agg_with_scalar_identity(groups, |s, g| unsafe { s.agg_last_non_null(g) })
1017    }
1018
1019    /// # Safety
1020    ///
1021    /// Does no bounds checks, groups must be correct.
1022    #[cfg(feature = "algorithm_group_by")]
1023    pub unsafe fn agg_n_unique(&self, groups: &GroupsType) -> Self {
1024        // @scalar-opt
1025        unsafe { self.as_materialized_series().agg_n_unique(groups) }.into()
1026    }
1027
1028    /// # Safety
1029    ///
1030    /// Does no bounds checks, groups must be correct.
1031    #[cfg(feature = "algorithm_group_by")]
1032    pub unsafe fn agg_quantile(
1033        &self,
1034        groups: &GroupsType,
1035        quantile: GroupQuantile<'_>,
1036        method: QuantileMethod,
1037    ) -> Self {
1038        // @scalar-opt
1039
1040        unsafe {
1041            self.as_materialized_series()
1042                .agg_quantile(groups, quantile, method)
1043        }
1044        .into()
1045    }
1046
1047    /// # Safety
1048    ///
1049    /// Does no bounds checks, groups must be correct.
1050    #[cfg(feature = "algorithm_group_by")]
1051    pub unsafe fn agg_median(&self, groups: &GroupsType) -> Self {
1052        self.agg_with_scalar_identity(groups, |s, g| unsafe { s.agg_median(g) })
1053    }
1054
1055    /// # Safety
1056    ///
1057    /// Does no bounds checks, groups must be correct.
1058    #[cfg(feature = "algorithm_group_by")]
1059    pub unsafe fn agg_var(&self, groups: &GroupsType, ddof: u8) -> Self {
1060        // @scalar-opt
1061        unsafe { self.as_materialized_series().agg_var(groups, ddof) }.into()
1062    }
1063
1064    /// # Safety
1065    ///
1066    /// Does no bounds checks, groups must be correct.
1067    #[cfg(feature = "algorithm_group_by")]
1068    pub unsafe fn agg_std(&self, groups: &GroupsType, ddof: u8) -> Self {
1069        // @scalar-opt
1070        unsafe { self.as_materialized_series().agg_std(groups, ddof) }.into()
1071    }
1072
1073    /// # Safety
1074    ///
1075    /// Does no bounds checks, groups must be correct.
1076    #[cfg(feature = "algorithm_group_by")]
1077    pub unsafe fn agg_list(&self, groups: &GroupsType) -> Self {
1078        // @scalar-opt
1079        unsafe { self.as_materialized_series().agg_list(groups) }.into()
1080    }
1081
1082    /// # Safety
1083    ///
1084    /// Does no bounds checks, groups must be correct.
1085    #[cfg(feature = "algorithm_group_by")]
1086    pub unsafe fn agg_valid_count(&self, groups: &GroupsType) -> Self {
1087        // @scalar-opt
1088        unsafe { self.as_materialized_series().agg_valid_count(groups) }.into()
1089    }
1090
1091    /// # Safety
1092    ///
1093    /// Does no bounds checks, groups must be correct.
1094    #[cfg(feature = "bitwise")]
1095    pub unsafe fn agg_and(&self, groups: &GroupsType) -> Self {
1096        self.agg_with_scalar_identity(groups, |s, g| unsafe { s.agg_and(g) })
1097    }
1098    /// # Safety
1099    ///
1100    /// Does no bounds checks, groups must be correct.
1101    #[cfg(feature = "bitwise")]
1102    pub unsafe fn agg_or(&self, groups: &GroupsType) -> Self {
1103        self.agg_with_scalar_identity(groups, |s, g| unsafe { s.agg_or(g) })
1104    }
1105    /// # Safety
1106    ///
1107    /// Does no bounds checks, groups must be correct.
1108    #[cfg(feature = "bitwise")]
1109    pub unsafe fn agg_xor(&self, groups: &GroupsType) -> Self {
1110        // @scalar-opt
1111        unsafe { self.as_materialized_series().agg_xor(groups) }.into()
1112    }
1113
1114    pub fn full_null(name: PlSmallStr, size: usize, dtype: &DataType) -> Self {
1115        Self::new_scalar(name, Scalar::new(dtype.clone(), AnyValue::Null), size)
1116    }
1117
1118    pub fn is_empty(&self) -> bool {
1119        self.len() == 0
1120    }
1121
1122    pub fn is_full_null(&self) -> bool {
1123        match self {
1124            Column::Series(s) => s.is_full_null(),
1125            Column::Scalar(s) => s.is_full_null(),
1126            Column::Dictionary(s) => s.null_count() == s.len(),
1127        }
1128    }
1129
1130    pub fn reverse(&self) -> Column {
1131        match self {
1132            Column::Series(s) => s.reverse().into(),
1133            Column::Scalar(_) => self.clone(),
1134            Column::Dictionary(s) => s.reverse().into(),
1135        }
1136    }
1137
1138    pub fn equals(&self, other: &Column) -> bool {
1139        // @scalar-opt
1140        self.as_materialized_series()
1141            .equals(other.as_materialized_series())
1142    }
1143
1144    pub fn equals_missing(&self, other: &Column) -> bool {
1145        // @scalar-opt
1146        self.as_materialized_series()
1147            .equals_missing(other.as_materialized_series())
1148    }
1149
1150    pub fn set_sorted_flag(&mut self, sorted: IsSorted) {
1151        // @scalar-opt
1152        match self {
1153            Column::Series(s) => s.set_sorted_flag(sorted),
1154            Column::Dictionary(s) => s.set_sorted_flag(sorted),
1155            Column::Scalar(_) => {},
1156        }
1157    }
1158
1159    pub fn get_flags(&self) -> StatisticsFlags {
1160        match self {
1161            Column::Series(s) => s.get_flags(),
1162            Column::Scalar(_) => {
1163                StatisticsFlags::IS_SORTED_ASC | StatisticsFlags::CAN_FAST_EXPLODE_LIST
1164            },
1165            Column::Dictionary(s) => {
1166                let mut flags = StatisticsFlags::empty();
1167                flags.set_sorted(s.is_sorted_flag());
1168                flags
1169            },
1170        }
1171    }
1172
1173    /// Returns whether the flags were set
1174    pub fn set_flags(&mut self, flags: StatisticsFlags) -> bool {
1175        match self {
1176            Column::Series(s) => {
1177                s.set_flags(flags);
1178                true
1179            },
1180            // Of the flags, a dictionary column keeps only sortedness.
1181            Column::Dictionary(s) => {
1182                s.set_sorted_flag(flags.is_sorted());
1183                true
1184            },
1185            Column::Scalar(_) => false,
1186        }
1187    }
1188
1189    pub fn vec_hash(
1190        &self,
1191        build_hasher: PlSeedableRandomStateQuality,
1192        buf: &mut Vec<u64>,
1193    ) -> PolarsResult<()> {
1194        // @scalar-opt?
1195        self.as_materialized_series().vec_hash(build_hasher, buf)
1196    }
1197
1198    pub fn vec_hash_combine(
1199        &self,
1200        build_hasher: PlSeedableRandomStateQuality,
1201        hashes: &mut [u64],
1202    ) -> PolarsResult<()> {
1203        // @scalar-opt?
1204        self.as_materialized_series()
1205            .vec_hash_combine(build_hasher, hashes)
1206    }
1207
1208    /// Try to append `other` to `self` without materializing, when both are scalar or both are
1209    /// dictionary columns.
1210    ///
1211    /// Returns whether that was possible.
1212    fn try_append_unmaterialized(&mut self, other: &Column) -> bool {
1213        match (&mut *self, other) {
1214            (Column::Scalar(lhs), Column::Scalar(rhs)) => lhs.try_append(rhs),
1215            (Column::Dictionary(lhs), Column::Dictionary(rhs)) => lhs.try_append(rhs),
1216            _ => false,
1217        }
1218    }
1219
1220    pub fn append(&mut self, other: &Column) -> PolarsResult<&mut Self> {
1221        if self.try_append_unmaterialized(other) {
1222            return Ok(self);
1223        }
1224
1225        self.into_materialized_series()
1226            .append(other.as_materialized_series())?;
1227        Ok(self)
1228    }
1229    pub fn append_owned(&mut self, other: Column) -> PolarsResult<&mut Self> {
1230        if self.try_append_unmaterialized(&other) {
1231            return Ok(self);
1232        }
1233
1234        self.into_materialized_series()
1235            .append_owned(other.take_materialized_series())?;
1236        Ok(self)
1237    }
1238
1239    pub fn arg_sort(&self, options: SortOptions) -> IdxCa {
1240        if self.is_empty() {
1241            return IdxCa::from_vec(self.name().clone(), Vec::new());
1242        }
1243
1244        if self.null_count() == self.len() {
1245            // If all key values are null, then they are all equal,
1246            // so we can just return the original dataframe.
1247            return IdxCa::from_iter_values(self.name().clone(), 0..self.len() as IdxSize);
1248        }
1249
1250        let is_sorted = Some(self.is_sorted_flag());
1251        let Some(is_sorted) = is_sorted.filter(|v| !matches!(v, IsSorted::Not)) else {
1252            return self.as_materialized_series().arg_sort(options);
1253        };
1254
1255        // Fast path: the data is sorted.
1256        let is_sorted_dsc = matches!(is_sorted, IsSorted::Descending);
1257        let invert = options.descending != is_sorted_dsc;
1258
1259        let mut values = Vec::with_capacity(self.len());
1260
1261        #[inline(never)]
1262        fn extend(
1263            start: IdxSize,
1264            end: IdxSize,
1265            slf: &Column,
1266            values: &mut Vec<IdxSize>,
1267            is_only_nulls: bool,
1268            invert: bool,
1269            maintain_order: bool,
1270        ) {
1271            debug_assert!(start <= end);
1272            debug_assert!(start as usize <= slf.len());
1273            debug_assert!(end as usize <= slf.len());
1274
1275            if !invert || is_only_nulls {
1276                values.extend(start..end);
1277                return;
1278            }
1279
1280            // If we don't have to maintain order but we have to invert. Just flip it around.
1281            if !maintain_order {
1282                values.extend((start..end).rev());
1283                return;
1284            }
1285
1286            // If we want to maintain order but we also need to invert, we need to invert
1287            // per group of items.
1288            //
1289            // @NOTE: Since the column is sorted, arg_unique can also take a fast path and
1290            // just do a single traversal.
1291            let arg_unique = slf
1292                .slice((start as usize, (end - start) as usize))
1293                .arg_unique()
1294                .unwrap();
1295
1296            assert!(!arg_unique.has_nulls());
1297
1298            let num_unique = arg_unique.len();
1299
1300            // Fast path: all items are unique.
1301            if num_unique == (end - start) as usize {
1302                values.extend((start..end).rev());
1303                return;
1304            }
1305
1306            if num_unique == 1 {
1307                values.extend(start..end);
1308                return;
1309            }
1310
1311            let mut prev_idx = end - start;
1312            for chunk in arg_unique.downcast_iter() {
1313                for &idx in chunk.values().as_slice().iter().rev() {
1314                    values.extend(start + idx..start + prev_idx);
1315                    prev_idx = idx;
1316                }
1317            }
1318        }
1319        macro_rules! extend {
1320            ($start:expr, $end:expr) => {
1321                extend!($start, $end, is_only_nulls = false);
1322            };
1323            ($start:expr, $end:expr, is_only_nulls = $is_only_nulls:expr) => {
1324                extend(
1325                    $start,
1326                    $end,
1327                    self,
1328                    &mut values,
1329                    $is_only_nulls,
1330                    invert,
1331                    options.maintain_order,
1332                );
1333            };
1334        }
1335
1336        let length = self.len() as IdxSize;
1337        let null_count = self.null_count() as IdxSize;
1338
1339        if null_count == 0 {
1340            extend!(0, length);
1341        } else {
1342            let has_nulls_last = self.get(self.len() - 1).unwrap().is_null();
1343            match (options.nulls_last, has_nulls_last) {
1344                (true, true) => {
1345                    // Current: Nulls last, Wanted: Nulls last
1346                    extend!(0, length - null_count);
1347                    extend!(length - null_count, length, is_only_nulls = true);
1348                },
1349                (true, false) => {
1350                    // Current: Nulls first, Wanted: Nulls last
1351                    extend!(null_count, length);
1352                    extend!(0, null_count, is_only_nulls = true);
1353                },
1354                (false, true) => {
1355                    // Current: Nulls last, Wanted: Nulls first
1356                    extend!(length - null_count, length, is_only_nulls = true);
1357                    extend!(0, length - null_count);
1358                },
1359                (false, false) => {
1360                    // Current: Nulls first, Wanted: Nulls first
1361                    extend!(0, null_count, is_only_nulls = true);
1362                    extend!(null_count, length);
1363                },
1364            }
1365        }
1366
1367        // @NOTE: This can theoretically be pushed into the previous operation but it is really
1368        // worth it... probably not...
1369        if let Some(limit) = options.limit {
1370            let limit = limit.min(length);
1371            values.truncate(limit as usize);
1372        }
1373
1374        IdxCa::from_vec(self.name().clone(), values)
1375    }
1376
1377    pub fn arg_sort_multiple(
1378        &self,
1379        by: &[Column],
1380        options: &SortMultipleOptions,
1381    ) -> PolarsResult<IdxCa> {
1382        // @scalar-opt
1383        self.as_materialized_series().arg_sort_multiple(by, options)
1384    }
1385
1386    pub fn arg_unique(&self) -> PolarsResult<IdxCa> {
1387        match self {
1388            Column::Scalar(s) => Ok(IdxCa::new_vec(s.name().clone(), vec![0])),
1389            _ => self.as_materialized_series().arg_unique(),
1390        }
1391    }
1392
1393    pub fn bit_repr(&self) -> Option<BitRepr> {
1394        // @scalar-opt
1395        self.as_materialized_series().bit_repr()
1396    }
1397
1398    pub fn into_frame(self) -> DataFrame {
1399        // SAFETY: A single-column dataframe cannot have length mismatches or duplicate names
1400        unsafe { DataFrame::new_unchecked(self.len(), vec![self]) }
1401    }
1402
1403    pub fn extend(&mut self, other: &Column) -> PolarsResult<&mut Self> {
1404        // `extend` only differs from `append` in the chunk layout of the result, and a
1405        // `ScalarColumn` has no chunks to lay out.
1406        if self.try_append_unmaterialized(other) {
1407            return Ok(self);
1408        }
1409
1410        self.into_materialized_series()
1411            .extend(other.as_materialized_series())?;
1412        Ok(self)
1413    }
1414
1415    pub fn rechunk(&self) -> Column {
1416        match self {
1417            Column::Series(s) => s.rechunk().into(),
1418            Column::Dictionary(s) => s.rechunk().into(),
1419            Column::Scalar(s) => {
1420                if s.lazy_as_materialized_series()
1421                    .filter(|x| x.n_chunks() > 1)
1422                    .is_some()
1423                {
1424                    Column::Scalar(ScalarColumn::new(
1425                        s.name().clone(),
1426                        s.scalar().clone(),
1427                        s.len(),
1428                    ))
1429                } else {
1430                    self.clone()
1431                }
1432            },
1433        }
1434    }
1435
1436    pub fn explode(&self, options: ExplodeOptions) -> PolarsResult<Column> {
1437        self.as_materialized_series()
1438            .explode(options)
1439            .map(Column::from)
1440    }
1441    pub fn implode(&self) -> PolarsResult<ListChunked> {
1442        self.as_materialized_series().implode()
1443    }
1444
1445    pub fn fill_null(&self, strategy: FillNullStrategy) -> PolarsResult<Self> {
1446        // @scalar-opt
1447        self.as_materialized_series()
1448            .fill_null(strategy)
1449            .map(Column::from)
1450    }
1451
1452    pub fn divide(&self, rhs: &Column) -> PolarsResult<Self> {
1453        // @scalar-opt
1454        self.as_materialized_series()
1455            .divide(rhs.as_materialized_series())
1456            .map(Column::from)
1457    }
1458
1459    pub fn shift(&self, periods: i64) -> Column {
1460        // @scalar-opt
1461        self.as_materialized_series().shift(periods).into()
1462    }
1463
1464    pub fn with_validity(&self, validity: Option<Bitmap>) -> Column {
1465        match self {
1466            Column::Series(_) | Column::Dictionary(_) => {
1467                let s = self.as_materialized_series();
1468                Column::from(s.with_validity(validity))
1469            },
1470            Column::Scalar(s) => match validity {
1471                Some(v) => Column::from(s.as_materialized_series().with_validity(Some(v))),
1472                None => Column::Scalar(s.clone()),
1473            },
1474        }
1475    }
1476
1477    pub fn mask(&self, validity: &Bitmap) -> Column {
1478        if validity.len() == 1 {
1479            if validity.get_bit(0) {
1480                self.clone()
1481            } else {
1482                Self::full_null(self.name().clone(), self.len(), self.dtype())
1483            }
1484        } else {
1485            Column::from(self.as_materialized_series().mask(validity))
1486        }
1487    }
1488
1489    #[cfg(feature = "zip_with")]
1490    pub fn zip_with(&self, mask: &BooleanChunked, other: &Self) -> PolarsResult<Self> {
1491        // @scalar-opt
1492        self.as_materialized_series()
1493            .zip_with(mask, other.as_materialized_series())
1494            .map(Self::from)
1495    }
1496
1497    #[cfg(feature = "zip_with")]
1498    pub fn zip_with_same_type(
1499        &self,
1500        mask: &ChunkedArray<BooleanType>,
1501        other: &Column,
1502    ) -> PolarsResult<Column> {
1503        // @scalar-opt
1504        self.as_materialized_series()
1505            .zip_with_same_type(mask, other.as_materialized_series())
1506            .map(Column::from)
1507    }
1508
1509    pub fn drop_nulls(&self) -> Column {
1510        match self {
1511            Column::Series(_) | Column::Dictionary(_) => {
1512                let s = self.as_materialized_series();
1513                s.drop_nulls().into_column()
1514            },
1515            Column::Scalar(s) => s.drop_nulls().into_column(),
1516        }
1517    }
1518
1519    /// Packs every element into a single-element list.
1520    pub fn to_unit_list(&self) -> Column {
1521        // @scalar-opt
1522        match self {
1523            Column::Series(_) | Column::Dictionary(_) => {
1524                let s = self.as_materialized_series();
1525                s.to_unit_list().into_column()
1526            },
1527            Column::Scalar(s) => s.to_unit_list().into_column(),
1528        }
1529    }
1530
1531    pub fn is_sorted_flag(&self) -> IsSorted {
1532        match self {
1533            Column::Series(_) => {
1534                let s = self.as_materialized_series();
1535                s.is_sorted_flag()
1536            },
1537            Column::Dictionary(s) => s.is_sorted_flag(),
1538            Column::Scalar(_) => IsSorted::Ascending,
1539        }
1540    }
1541
1542    pub fn unique(&self) -> PolarsResult<Column> {
1543        match self {
1544            Column::Series(_) | Column::Dictionary(_) => {
1545                let s = self.as_materialized_series();
1546                s.unique().map(Column::from)
1547            },
1548            Column::Scalar(s) => {
1549                _ = s.as_single_value_series().unique()?;
1550                if s.is_empty() {
1551                    return Ok(s.clone().into_column());
1552                }
1553
1554                Ok(s.resize(1).into_column())
1555            },
1556        }
1557    }
1558    pub fn unique_stable(&self) -> PolarsResult<Column> {
1559        match self {
1560            Column::Series(_) | Column::Dictionary(_) => {
1561                let s = self.as_materialized_series();
1562                s.unique_stable().map(Column::from)
1563            },
1564            Column::Scalar(s) => {
1565                _ = s.as_single_value_series().unique_stable()?;
1566                if s.is_empty() {
1567                    return Ok(s.clone().into_column());
1568                }
1569
1570                Ok(s.resize(1).into_column())
1571            },
1572        }
1573    }
1574
1575    pub fn reshape_list(&self, dimensions: &[ReshapeDimension]) -> PolarsResult<Self> {
1576        // @scalar-opt
1577        self.as_materialized_series()
1578            .reshape_list(dimensions)
1579            .map(Self::from)
1580    }
1581
1582    #[cfg(feature = "dtype-array")]
1583    pub fn reshape_array(&self, dimensions: &[ReshapeDimension]) -> PolarsResult<Self> {
1584        // @scalar-opt
1585        self.as_materialized_series()
1586            .reshape_array(dimensions)
1587            .map(Self::from)
1588    }
1589
1590    pub fn sort(&self, sort_options: SortOptions) -> PolarsResult<Self> {
1591        // @scalar-opt
1592        self.as_materialized_series()
1593            .sort(sort_options)
1594            .map(Self::from)
1595    }
1596
1597    pub fn filter(&self, filter: &BooleanChunked) -> PolarsResult<Self> {
1598        match self {
1599            Column::Series(s) => s.filter(filter).map(Column::from),
1600            Column::Dictionary(s) => s.filter(filter).map(Column::from),
1601            Column::Scalar(s) => {
1602                if s.is_empty() {
1603                    return Ok(s.clone().into_column());
1604                }
1605
1606                // Broadcasting
1607                if filter.len() == 1 {
1608                    return match filter.get(0) {
1609                        Some(true) => Ok(s.clone().into_column()),
1610                        _ => Ok(s.resize(0).into_column()),
1611                    };
1612                }
1613
1614                Ok(s.resize(filter.sum().unwrap() as usize).into_column())
1615            },
1616        }
1617    }
1618
1619    #[cfg(feature = "random")]
1620    pub fn shuffle(&self, seed: Option<u64>) -> Self {
1621        // @scalar-opt
1622        self.as_materialized_series().shuffle(seed).into()
1623    }
1624
1625    #[cfg(feature = "random")]
1626    pub fn sample_frac(
1627        &self,
1628        frac: f64,
1629        with_replacement: bool,
1630        shuffle: Option<bool>,
1631        seed: Option<u64>,
1632    ) -> PolarsResult<Self> {
1633        self.as_materialized_series()
1634            .sample_frac(frac, with_replacement, shuffle, seed)
1635            .map(Self::from)
1636    }
1637
1638    #[cfg(feature = "random")]
1639    pub fn sample_n(
1640        &self,
1641        n: usize,
1642        with_replacement: bool,
1643        shuffle: Option<bool>,
1644        seed: Option<u64>,
1645    ) -> PolarsResult<Self> {
1646        self.as_materialized_series()
1647            .sample_n(n, with_replacement, shuffle, seed)
1648            .map(Self::from)
1649    }
1650
1651    pub fn gather_every(&self, n: usize, offset: usize) -> PolarsResult<Column> {
1652        polars_ensure!(n > 0, InvalidOperation: "gather_every(n): n should be positive");
1653        if self.len().saturating_sub(offset) == 0 {
1654            return Ok(self.clear());
1655        }
1656
1657        match self {
1658            Column::Series(_) | Column::Dictionary(_) => {
1659                let s = self.as_materialized_series();
1660                Ok(s.gather_every(n, offset)?.into())
1661            },
1662            Column::Scalar(s) => {
1663                let total = s.len() - offset;
1664                Ok(s.resize(1 + (total - 1) / n).into())
1665            },
1666        }
1667    }
1668
1669    pub fn extend_constant(&self, value: AnyValue, n: usize) -> PolarsResult<Self> {
1670        if self.is_empty() {
1671            return Ok(Self::new_scalar(
1672                self.name().clone(),
1673                Scalar::new(self.dtype().clone(), value.into_static()),
1674                n,
1675            ));
1676        }
1677
1678        match self {
1679            Column::Series(_) | Column::Dictionary(_) => {
1680                let s = self.as_materialized_series();
1681                s.extend_constant(value, n).map(Column::from)
1682            },
1683            Column::Scalar(s) => {
1684                if s.scalar().as_any_value() == value {
1685                    Ok(s.resize(s.len() + n).into())
1686                } else {
1687                    s.as_materialized_series()
1688                        .extend_constant(value, n)
1689                        .map(Column::from)
1690                }
1691            },
1692        }
1693    }
1694
1695    pub fn is_finite(&self) -> PolarsResult<BooleanChunked> {
1696        self.try_map_unary_elementwise_to_bool(|s| s.is_finite())
1697    }
1698    pub fn is_infinite(&self) -> PolarsResult<BooleanChunked> {
1699        self.try_map_unary_elementwise_to_bool(|s| s.is_infinite())
1700    }
1701    pub fn is_nan(&self) -> PolarsResult<BooleanChunked> {
1702        self.try_map_unary_elementwise_to_bool(|s| s.is_nan())
1703    }
1704    pub fn is_not_nan(&self) -> PolarsResult<BooleanChunked> {
1705        self.try_map_unary_elementwise_to_bool(|s| s.is_not_nan())
1706    }
1707
1708    pub fn wrapping_trunc_div_scalar<T>(&self, rhs: T) -> Self
1709    where
1710        T: Num + NumCast,
1711    {
1712        // @scalar-opt
1713        self.as_materialized_series()
1714            .wrapping_trunc_div_scalar(rhs)
1715            .into()
1716    }
1717
1718    pub fn product(&self) -> PolarsResult<Scalar> {
1719        // @scalar-opt
1720        self.as_materialized_series().product()
1721    }
1722
1723    #[inline]
1724    pub fn get(&self, index: usize) -> PolarsResult<AnyValue<'_>> {
1725        polars_ensure!(index < self.len(), oob = index, self.len());
1726
1727        // SAFETY: Bounds check done just before.
1728        Ok(unsafe { self.get_unchecked(index) })
1729    }
1730    /// # Safety
1731    ///
1732    /// Does not perform bounds check on `index`
1733    #[inline(always)]
1734    pub unsafe fn get_unchecked(&self, index: usize) -> AnyValue<'_> {
1735        debug_assert!(index < self.len());
1736
1737        match self {
1738            Column::Series(s) => unsafe { s.get_unchecked(index) },
1739            Column::Scalar(s) => s.scalar().as_any_value(),
1740            Column::Dictionary(s) => match unsafe { s.codes().get_unchecked(index) } {
1741                Some(code) => {
1742                    AnyValue::String(unsafe { s.dict().values().value_unchecked(code as usize) })
1743                },
1744                None => AnyValue::Null,
1745            },
1746        }
1747    }
1748
1749    #[cfg(feature = "object")]
1750    pub fn get_object(
1751        &self,
1752        index: usize,
1753    ) -> Option<&dyn crate::chunked_array::object::PolarsObjectSafe> {
1754        self.as_materialized_series().get_object(index)
1755    }
1756
1757    pub fn bitand(&self, rhs: &Self) -> PolarsResult<Self> {
1758        self.try_apply_broadcasting_binary_elementwise(rhs, |l, r| l & r)
1759    }
1760    pub fn bitor(&self, rhs: &Self) -> PolarsResult<Self> {
1761        self.try_apply_broadcasting_binary_elementwise(rhs, |l, r| l | r)
1762    }
1763    pub fn bitxor(&self, rhs: &Self) -> PolarsResult<Self> {
1764        self.try_apply_broadcasting_binary_elementwise(rhs, |l, r| l ^ r)
1765    }
1766
1767    pub fn try_add_owned(self, other: Self) -> PolarsResult<Self> {
1768        match (self, other) {
1769            (Column::Series(lhs), Column::Series(rhs)) => {
1770                lhs.take().try_add_owned(rhs.take()).map(Column::from)
1771            },
1772            (lhs, rhs) => lhs + rhs,
1773        }
1774    }
1775    pub fn try_sub_owned(self, other: Self) -> PolarsResult<Self> {
1776        match (self, other) {
1777            (Column::Series(lhs), Column::Series(rhs)) => {
1778                lhs.take().try_sub_owned(rhs.take()).map(Column::from)
1779            },
1780            (lhs, rhs) => lhs - rhs,
1781        }
1782    }
1783    pub fn try_mul_owned(self, other: Self) -> PolarsResult<Self> {
1784        match (self, other) {
1785            (Column::Series(lhs), Column::Series(rhs)) => {
1786                lhs.take().try_mul_owned(rhs.take()).map(Column::from)
1787            },
1788            (lhs, rhs) => lhs * rhs,
1789        }
1790    }
1791
1792    pub(crate) fn str_value(&self, index: usize) -> PolarsResult<Cow<'_, str>> {
1793        Ok(self.get(index)?.str_value())
1794    }
1795
1796    pub fn min_reduce(&self) -> PolarsResult<Scalar> {
1797        match self {
1798            Column::Series(_) | Column::Dictionary(_) => {
1799                let s = self.as_materialized_series();
1800                s.min_reduce()
1801            },
1802            Column::Scalar(s) => {
1803                // We don't really want to deal with handling the full semantics here so we just
1804                // cast to a single value series. This is a tiny bit wasteful, but probably fine.
1805                s.as_single_value_series().min_reduce()
1806            },
1807        }
1808    }
1809    pub fn max_reduce(&self) -> PolarsResult<Scalar> {
1810        match self {
1811            Column::Series(_) | Column::Dictionary(_) => {
1812                let s = self.as_materialized_series();
1813                s.max_reduce()
1814            },
1815            Column::Scalar(s) => {
1816                // We don't really want to deal with handling the full semantics here so we just
1817                // cast to a single value series. This is a tiny bit wasteful, but probably fine.
1818                s.as_single_value_series().max_reduce()
1819            },
1820        }
1821    }
1822    pub fn median_reduce(&self) -> PolarsResult<Scalar> {
1823        match self {
1824            Column::Series(_) | Column::Dictionary(_) => {
1825                let s = self.as_materialized_series();
1826                s.median_reduce()
1827            },
1828            Column::Scalar(s) => {
1829                // We don't really want to deal with handling the full semantics here so we just
1830                // cast to a single value series. This is a tiny bit wasteful, but probably fine.
1831                s.as_single_value_series().median_reduce()
1832            },
1833        }
1834    }
1835    pub fn mean_reduce(&self) -> PolarsResult<Scalar> {
1836        match self {
1837            Column::Series(_) | Column::Dictionary(_) => {
1838                let s = self.as_materialized_series();
1839                s.mean_reduce()
1840            },
1841            Column::Scalar(s) => {
1842                // We don't really want to deal with handling the full semantics here so we just
1843                // cast to a single value series. This is a tiny bit wasteful, but probably fine.
1844                s.as_single_value_series().mean_reduce()
1845            },
1846        }
1847    }
1848    pub fn std_reduce(&self, ddof: u8) -> PolarsResult<Scalar> {
1849        match self {
1850            Column::Series(_) | Column::Dictionary(_) => {
1851                let s = self.as_materialized_series();
1852                s.std_reduce(ddof)
1853            },
1854            Column::Scalar(s) => {
1855                // We don't really want to deal with handling the full semantics here so we just
1856                // cast to a small series. This is a tiny bit wasteful, but probably fine.
1857                let n = s.len().min(ddof as usize + 1);
1858                s.as_n_values_series(n).std_reduce(ddof)
1859            },
1860        }
1861    }
1862    pub fn var_reduce(&self, ddof: u8) -> PolarsResult<Scalar> {
1863        match self {
1864            Column::Series(_) | Column::Dictionary(_) => {
1865                let s = self.as_materialized_series();
1866                s.var_reduce(ddof)
1867            },
1868            Column::Scalar(s) => {
1869                // We don't really want to deal with handling the full semantics here so we just
1870                // cast to a small series. This is a tiny bit wasteful, but probably fine.
1871                let n = s.len().min(ddof as usize + 1);
1872                s.as_n_values_series(n).var_reduce(ddof)
1873            },
1874        }
1875    }
1876    pub fn sum_reduce(&self) -> PolarsResult<Scalar> {
1877        // @scalar-opt
1878        self.as_materialized_series().sum_reduce()
1879    }
1880    pub fn and_reduce(&self) -> PolarsResult<Scalar> {
1881        match self {
1882            Column::Series(_) | Column::Dictionary(_) => {
1883                let s = self.as_materialized_series();
1884                s.and_reduce()
1885            },
1886            Column::Scalar(s) => {
1887                // We don't really want to deal with handling the full semantics here so we just
1888                // cast to a single value series. This is a tiny bit wasteful, but probably fine.
1889                s.as_single_value_series().and_reduce()
1890            },
1891        }
1892    }
1893    pub fn or_reduce(&self) -> PolarsResult<Scalar> {
1894        match self {
1895            Column::Series(_) | Column::Dictionary(_) => {
1896                let s = self.as_materialized_series();
1897                s.or_reduce()
1898            },
1899            Column::Scalar(s) => {
1900                // We don't really want to deal with handling the full semantics here so we just
1901                // cast to a single value series. This is a tiny bit wasteful, but probably fine.
1902                s.as_single_value_series().or_reduce()
1903            },
1904        }
1905    }
1906    pub fn xor_reduce(&self) -> PolarsResult<Scalar> {
1907        match self {
1908            Column::Series(_) | Column::Dictionary(_) => {
1909                let s = self.as_materialized_series();
1910                s.xor_reduce()
1911            },
1912            Column::Scalar(s) => {
1913                // We don't really want to deal with handling the full semantics here so we just
1914                // cast to a single value series. This is a tiny bit wasteful, but probably fine.
1915                //
1916                // We have to deal with the fact that xor is 0 if there is an even number of
1917                // elements and the value if there is an odd number of elements. If there are zero
1918                // elements the result should be `null`.
1919                s.as_n_values_series(2 - s.len() % 2).xor_reduce()
1920            },
1921        }
1922    }
1923    pub fn n_unique(&self) -> PolarsResult<usize> {
1924        match self {
1925            Column::Series(_) | Column::Dictionary(_) => {
1926                let s = self.as_materialized_series();
1927                s.n_unique()
1928            },
1929            Column::Scalar(s) => s.as_single_value_series().n_unique(),
1930        }
1931    }
1932
1933    pub fn quantile_reduce(&self, quantile: f64, method: QuantileMethod) -> PolarsResult<Scalar> {
1934        self.as_materialized_series()
1935            .quantile_reduce(quantile, method)
1936    }
1937
1938    pub fn quantiles_reduce(
1939        &self,
1940        quantiles: &[f64],
1941        method: QuantileMethod,
1942    ) -> PolarsResult<Scalar> {
1943        self.as_materialized_series()
1944            .quantiles_reduce(quantiles, method)
1945    }
1946
1947    /// The estimated memory of the column in bytes. Without `expanded`, a scalar column that is
1948    /// not materialized counts only its value.
1949    pub fn estimated_size(&self, expanded: bool) -> usize {
1950        match self {
1951            Column::Series(s) => s.estimated_size(),
1952            Column::Scalar(s) => s.estimated_size(expanded),
1953            Column::Dictionary(s) => s.estimated_size(),
1954        }
1955    }
1956
1957    pub fn sort_with(&self, options: SortOptions) -> PolarsResult<Self> {
1958        match self {
1959            Column::Series(_) | Column::Dictionary(_) => {
1960                let s = self.as_materialized_series();
1961                s.sort_with(options).map(Self::from)
1962            },
1963            Column::Scalar(s) => {
1964                // This makes this function throw the same errors as Series::sort_with
1965                _ = s.as_single_value_series().sort_with(options)?;
1966
1967                Ok(self.clone())
1968            },
1969        }
1970    }
1971
1972    pub fn map_unary_elementwise_to_bool(
1973        &self,
1974        f: impl Fn(&Series) -> BooleanChunked,
1975    ) -> BooleanChunked {
1976        self.try_map_unary_elementwise_to_bool(|s| Ok(f(s)))
1977            .unwrap()
1978    }
1979    pub fn try_map_unary_elementwise_to_bool(
1980        &self,
1981        f: impl Fn(&Series) -> PolarsResult<BooleanChunked>,
1982    ) -> PolarsResult<BooleanChunked> {
1983        match self {
1984            Column::Series(_) | Column::Dictionary(_) => {
1985                let s = self.as_materialized_series();
1986                f(s)
1987            },
1988            Column::Scalar(s) => Ok(f(&s.as_single_value_series())?.new_from_index(0, s.len())),
1989        }
1990    }
1991
1992    pub fn apply_unary_elementwise(&self, f: impl Fn(&Series) -> Series) -> Column {
1993        self.try_apply_unary_elementwise(|s| Ok(f(s))).unwrap()
1994    }
1995    pub fn try_apply_unary_elementwise(
1996        &self,
1997        f: impl Fn(&Series) -> PolarsResult<Series>,
1998    ) -> PolarsResult<Column> {
1999        match self {
2000            Column::Series(_) | Column::Dictionary(_) => {
2001                let s = self.as_materialized_series();
2002                f(s).map(Column::from)
2003            },
2004            Column::Scalar(s) => Ok(ScalarColumn::from_single_value_series(
2005                f(&s.as_single_value_series())?,
2006                s.len(),
2007            )
2008            .into()),
2009        }
2010    }
2011
2012    pub fn apply_broadcasting_binary_elementwise(
2013        &self,
2014        other: &Self,
2015        op: impl Fn(&Series, &Series) -> Series,
2016    ) -> PolarsResult<Column> {
2017        self.try_apply_broadcasting_binary_elementwise(other, |lhs, rhs| Ok(op(lhs, rhs)))
2018    }
2019    pub fn try_apply_broadcasting_binary_elementwise(
2020        &self,
2021        other: &Self,
2022        op: impl Fn(&Series, &Series) -> PolarsResult<Series>,
2023    ) -> PolarsResult<Column> {
2024        // Here we rely on the underlying broadcast operations.
2025        let length = broadcast_len([self, other])
2026            .context("cannot do a binary operation on columns of different lengths")?;
2027        match (self, other) {
2028            (Column::Scalar(lhs), Column::Scalar(rhs)) => {
2029                let lhs = lhs.as_single_value_series();
2030                let rhs = rhs.as_single_value_series();
2031
2032                Ok(ScalarColumn::from_single_value_series(op(&lhs, &rhs)?, length).into_column())
2033            },
2034            (lhs, Column::Scalar(rhs)) => {
2035                op(lhs.as_materialized_series(), &rhs.as_single_value_series()).map(Column::from)
2036            },
2037            (Column::Scalar(lhs), rhs) => {
2038                op(&lhs.as_single_value_series(), rhs.as_materialized_series()).map(Column::from)
2039            },
2040            (lhs, rhs) => {
2041                op(lhs.as_materialized_series(), rhs.as_materialized_series()).map(Column::from)
2042            },
2043        }
2044    }
2045
2046    pub fn apply_binary_elementwise(
2047        &self,
2048        other: &Self,
2049        f: impl Fn(&Series, &Series) -> Series,
2050        f_lb: impl Fn(&Scalar, &Series) -> Series,
2051        f_rb: impl Fn(&Series, &Scalar) -> Series,
2052    ) -> Column {
2053        self.try_apply_binary_elementwise(
2054            other,
2055            |lhs, rhs| Ok(f(lhs, rhs)),
2056            |lhs, rhs| Ok(f_lb(lhs, rhs)),
2057            |lhs, rhs| Ok(f_rb(lhs, rhs)),
2058        )
2059        .unwrap()
2060    }
2061    pub fn try_apply_binary_elementwise(
2062        &self,
2063        other: &Self,
2064        f: impl Fn(&Series, &Series) -> PolarsResult<Series>,
2065        f_lb: impl Fn(&Scalar, &Series) -> PolarsResult<Series>,
2066        f_rb: impl Fn(&Series, &Scalar) -> PolarsResult<Series>,
2067    ) -> PolarsResult<Column> {
2068        debug_assert_eq!(self.len(), other.len());
2069
2070        match (self, other) {
2071            (Column::Scalar(lhs), Column::Scalar(rhs)) => {
2072                let lhs = lhs.as_single_value_series();
2073                let rhs = rhs.as_single_value_series();
2074
2075                Ok(
2076                    ScalarColumn::from_single_value_series(f(&lhs, &rhs)?, self.len())
2077                        .into_column(),
2078                )
2079            },
2080            (lhs, Column::Scalar(rhs)) => {
2081                f_rb(lhs.as_materialized_series(), rhs.scalar()).map(Column::from)
2082            },
2083            (Column::Scalar(lhs), rhs) => {
2084                f_lb(lhs.scalar(), rhs.as_materialized_series()).map(Column::from)
2085            },
2086            (lhs, rhs) => {
2087                f(lhs.as_materialized_series(), rhs.as_materialized_series()).map(Column::from)
2088            },
2089        }
2090    }
2091
2092    #[cfg(feature = "approx_unique")]
2093    pub fn approx_n_unique(&self) -> PolarsResult<IdxSize> {
2094        match self {
2095            Column::Series(_) | Column::Dictionary(_) => {
2096                let s = self.as_materialized_series();
2097                s.approx_n_unique()
2098            },
2099            Column::Scalar(s) => {
2100                // @NOTE: We do this for the error handling.
2101                s.as_single_value_series().approx_n_unique()?;
2102                Ok(if s.is_empty() { 0 } else { 1 })
2103            },
2104        }
2105    }
2106
2107    pub fn n_chunks(&self) -> usize {
2108        match self {
2109            Column::Series(s) => s.n_chunks(),
2110            Column::Dictionary(s) => s
2111                .lazy_as_materialized_series()
2112                .map_or(s.codes().chunks().len(), |x| x.n_chunks()),
2113            // A materialized scalar column can hold more than one chunk.
2114            Column::Scalar(s) => s.lazy_as_materialized_series().map_or(1, |x| x.n_chunks()),
2115        }
2116    }
2117
2118    #[expect(clippy::wrong_self_convention)]
2119    pub(crate) fn into_total_ord_inner<'a>(&'a self) -> Box<dyn TotalOrdInner + 'a> {
2120        // @scalar-opt
2121        self.as_materialized_series().into_total_ord_inner()
2122    }
2123
2124    pub fn rechunk_to_arrow(self, compat_level: CompatLevel) -> Box<dyn Array> {
2125        // Rechunk to one chunk if necessary
2126        let mut series = self.take_materialized_series();
2127        if series.n_chunks() > 1 {
2128            series = series.rechunk();
2129        }
2130        series.to_arrow(0, compat_level)
2131    }
2132
2133    pub fn trim_lists_to_normalized_offsets(&self) -> Option<Column> {
2134        self.as_materialized_series()
2135            .trim_lists_to_normalized_offsets()
2136            .map(Column::from)
2137    }
2138
2139    pub fn propagate_nulls(&self) -> Option<Column> {
2140        self.as_materialized_series()
2141            .propagate_nulls()
2142            .map(Column::from)
2143    }
2144
2145    pub fn deposit(&self, validity: &Bitmap) -> Column {
2146        self.as_materialized_series()
2147            .deposit(validity)
2148            .into_column()
2149    }
2150
2151    pub fn rechunk_validity(&self) -> Option<Bitmap> {
2152        // @scalar-opt
2153        self.as_materialized_series().rechunk_validity()
2154    }
2155
2156    pub fn unique_id(&self) -> PolarsResult<(IdxSize, Vec<IdxSize>)> {
2157        self.as_materialized_series().unique_id()
2158    }
2159}
2160
2161impl Default for Column {
2162    fn default() -> Self {
2163        Self::new_scalar(
2164            PlSmallStr::EMPTY,
2165            Scalar::new(DataType::Int64, AnyValue::Null),
2166            0,
2167        )
2168    }
2169}
2170
2171impl PartialEq for Column {
2172    fn eq(&self, other: &Self) -> bool {
2173        // @scalar-opt
2174        self.as_materialized_series()
2175            .eq(other.as_materialized_series())
2176    }
2177}
2178
2179impl From<Series> for Column {
2180    #[inline]
2181    fn from(series: Series) -> Self {
2182        // We instantiate a Scalar Column if the Series length is 1. This makes it possible for
2183        // future operations to be faster.
2184        if series.len() == 1 {
2185            return Self::Scalar(ScalarColumn::unit_scalar_from_series(series));
2186        }
2187
2188        Self::Series(SeriesColumn::new(series))
2189    }
2190}
2191
2192impl<T: IntoSeries> IntoColumn for T {
2193    #[inline]
2194    fn into_column(self) -> Column {
2195        self.into_series().into()
2196    }
2197}
2198
2199impl IntoColumn for Column {
2200    #[inline(always)]
2201    fn into_column(self) -> Column {
2202        self
2203    }
2204}
2205
2206impl BroadcastLength for Column {
2207    fn _broadcast_len(&self) -> usize {
2208        self.len()
2209    }
2210
2211    fn _column_name(&self) -> Option<&str> {
2212        Some(self.name())
2213    }
2214}
2215
2216/// We don't want to serialize the scalar columns. So this helps pretend that columns are always
2217/// initialized without implementing From<Column> for Series.
2218///
2219/// Those casts should be explicit.
2220#[derive(Clone)]
2221#[cfg_attr(feature = "serde", derive(serde::Serialize))]
2222#[cfg_attr(feature = "serde", serde(into = "Series"))]
2223struct _SerdeSeries(Series);
2224
2225impl From<Column> for _SerdeSeries {
2226    #[inline]
2227    fn from(value: Column) -> Self {
2228        Self(value.take_materialized_series())
2229    }
2230}
2231
2232impl From<_SerdeSeries> for Series {
2233    #[inline]
2234    fn from(value: _SerdeSeries) -> Self {
2235        value.0
2236    }
2237}