polars_core/series/implementations/
null.rs

1use std::any::Any;
2
3use polars_error::constants::LENGTH_LIMIT_MSG;
4
5use self::compare_inner::TotalOrdInner;
6use super::*;
7use crate::chunked_array::ops::compare_inner::{IntoTotalEqInner, NonNull, TotalEqInner};
8use crate::chunked_array::ops::sort::arg_sort_multiple::arg_sort_multiple_impl;
9use crate::prelude::*;
10use crate::series::private::{PrivateSeries, PrivateSeriesNumeric};
11use crate::series::*;
12
13impl Series {
14    pub fn new_null(name: PlSmallStr, len: usize) -> Series {
15        NullChunked::new(name, len).into_series()
16    }
17}
18
19#[derive(Clone)]
20pub struct NullChunked {
21    pub(crate) name: PlSmallStr,
22    length: IdxSize,
23    // we still need chunks as many series consumers expect
24    // chunks to be there
25    chunks: Vec<ArrayRef>,
26}
27
28impl NullChunked {
29    pub(crate) fn new(name: PlSmallStr, len: usize) -> Self {
30        Self {
31            name,
32            length: len as IdxSize,
33            chunks: vec![Box::new(arrow::array::NullArray::new(
34                ArrowDataType::Null,
35                len,
36            ))],
37        }
38    }
39
40    pub fn len(&self) -> usize {
41        self.length as usize
42    }
43
44    pub fn is_empty(&self) -> bool {
45        self.length == 0
46    }
47}
48impl PrivateSeriesNumeric for NullChunked {
49    fn bit_repr(&self) -> Option<BitRepr> {
50        Some(BitRepr::U32(UInt32Chunked::full_null(
51            self.name.clone(),
52            self.len(),
53        )))
54    }
55}
56
57impl PrivateSeries for NullChunked {
58    fn compute_len(&mut self) {
59        fn inner(chunks: &[ArrayRef]) -> usize {
60            match chunks.len() {
61                // fast path
62                1 => chunks[0].len(),
63                _ => chunks.iter().fold(0, |acc, arr| acc + arr.len()),
64            }
65        }
66        self.length = IdxSize::try_from(inner(&self.chunks)).expect(LENGTH_LIMIT_MSG);
67    }
68    fn _field(&self) -> Cow<'_, Field> {
69        Cow::Owned(Field::new(self.name().clone(), DataType::Null))
70    }
71
72    #[allow(unused)]
73    fn _set_flags(&mut self, flags: StatisticsFlags) {}
74
75    fn _dtype(&self) -> &DataType {
76        &DataType::Null
77    }
78
79    #[cfg(feature = "zip_with")]
80    fn zip_with_same_type(&self, mask: &BooleanChunked, other: &Series) -> PolarsResult<Series> {
81        let len = match (self.len(), mask.len(), other.len()) {
82            (a, b, c) if a == b && b == c => a,
83            (1, a, b) | (a, 1, b) | (a, b, 1) if a == b => a,
84            (a, 1, 1) | (1, a, 1) | (1, 1, a) => a,
85            (_, 0, _) => 0,
86            _ => {
87                polars_bail!(ShapeMismatch: "shapes of `self`, `mask` and `other` are not suitable for `zip_with` operation")
88            },
89        };
90
91        Ok(Self::new(self.name().clone(), len).into_series())
92    }
93
94    fn into_total_eq_inner<'a>(&'a self) -> Box<dyn TotalEqInner + 'a> {
95        IntoTotalEqInner::into_total_eq_inner(self)
96    }
97    fn into_total_ord_inner<'a>(&'a self) -> Box<dyn TotalOrdInner + 'a> {
98        IntoTotalOrdInner::into_total_ord_inner(self)
99    }
100
101    fn subtract(&self, _rhs: &Series) -> PolarsResult<Series> {
102        null_arithmetic(self, _rhs, "subtract")
103    }
104
105    fn add_to(&self, _rhs: &Series) -> PolarsResult<Series> {
106        null_arithmetic(self, _rhs, "add_to")
107    }
108    fn multiply(&self, _rhs: &Series) -> PolarsResult<Series> {
109        null_arithmetic(self, _rhs, "multiply")
110    }
111    fn divide(&self, _rhs: &Series) -> PolarsResult<Series> {
112        null_arithmetic(self, _rhs, "divide")
113    }
114    fn remainder(&self, _rhs: &Series) -> PolarsResult<Series> {
115        null_arithmetic(self, _rhs, "remainder")
116    }
117
118    #[cfg(feature = "algorithm_group_by")]
119    fn group_tuples(&self, _multithreaded: bool, _sorted: bool) -> PolarsResult<GroupsType> {
120        Ok(if self.is_empty() {
121            GroupsType::default()
122        } else {
123            GroupsType::Slice {
124                groups: vec![[0, self.length]],
125                overlapping: false,
126            }
127        })
128    }
129
130    #[cfg(feature = "algorithm_group_by")]
131    unsafe fn agg_list(&self, groups: &GroupsType) -> Series {
132        AggList::agg_list(self, groups)
133    }
134
135    fn _get_flags(&self) -> StatisticsFlags {
136        StatisticsFlags::empty()
137    }
138
139    fn vec_hash(
140        &self,
141        random_state: PlSeedableRandomStateQuality,
142        buf: &mut Vec<u64>,
143    ) -> PolarsResult<()> {
144        VecHash::vec_hash(self, random_state, buf)?;
145        Ok(())
146    }
147
148    fn vec_hash_combine(
149        &self,
150        build_hasher: PlSeedableRandomStateQuality,
151        hashes: &mut [u64],
152    ) -> PolarsResult<()> {
153        VecHash::vec_hash_combine(self, build_hasher, hashes)?;
154        Ok(())
155    }
156
157    fn arg_sort_multiple(
158        &self,
159        by: &[Column],
160        options: &SortMultipleOptions,
161    ) -> PolarsResult<IdxCa> {
162        let vals = (0..self.len())
163            .map(|i| (i as IdxSize, NonNull(())))
164            .collect();
165        arg_sort_multiple_impl(vals, by, options)
166    }
167}
168
169fn null_arithmetic(lhs: &NullChunked, rhs: &Series, op: &str) -> PolarsResult<Series> {
170    let output_len = match (lhs.len(), rhs.len()) {
171        (1, len_r) => len_r,
172        (len_l, 1) => len_l,
173        (len_l, len_r) if len_l == len_r => len_l,
174        _ => polars_bail!(ComputeError: "Cannot {:?} two series of different lengths.", op),
175    };
176    Ok(NullChunked::new(lhs.name().clone(), output_len).into_series())
177}
178
179impl SeriesTrait for NullChunked {
180    fn name(&self) -> &PlSmallStr {
181        &self.name
182    }
183
184    fn rename(&mut self, name: PlSmallStr) {
185        self.name = name
186    }
187
188    fn chunks(&self) -> &Vec<ArrayRef> {
189        &self.chunks
190    }
191    unsafe fn chunks_mut(&mut self) -> &mut Vec<ArrayRef> {
192        &mut self.chunks
193    }
194
195    fn chunk_lengths(&self) -> ChunkLenIter<'_> {
196        self.chunks.iter().map(|chunk| chunk.len())
197    }
198
199    fn take(&self, indices: &IdxCa) -> PolarsResult<Series> {
200        Ok(NullChunked::new(self.name.clone(), indices.len()).into_series())
201    }
202
203    unsafe fn take_unchecked(&self, indices: &IdxCa) -> Series {
204        NullChunked::new(self.name.clone(), indices.len()).into_series()
205    }
206
207    fn take_slice(&self, indices: &[IdxSize]) -> PolarsResult<Series> {
208        Ok(NullChunked::new(self.name.clone(), indices.len()).into_series())
209    }
210
211    unsafe fn take_slice_unchecked(&self, indices: &[IdxSize]) -> Series {
212        NullChunked::new(self.name.clone(), indices.len()).into_series()
213    }
214
215    fn deposit(&self, validity: &Bitmap) -> Series {
216        assert_eq!(validity.set_bits(), 0);
217        self.clone().into_series()
218    }
219
220    fn len(&self) -> usize {
221        self.length as usize
222    }
223
224    fn has_nulls(&self) -> bool {
225        !self.is_empty()
226    }
227
228    fn rechunk(&self) -> Series {
229        NullChunked::new(self.name.clone(), self.len()).into_series()
230    }
231
232    fn drop_nulls(&self) -> Series {
233        NullChunked::new(self.name.clone(), 0).into_series()
234    }
235
236    fn cast(&self, dtype: &DataType, _cast_options: CastOptions) -> PolarsResult<Series> {
237        Ok(Series::full_null(self.name.clone(), self.len(), dtype))
238    }
239
240    fn null_count(&self) -> usize {
241        self.len()
242    }
243
244    #[cfg(feature = "algorithm_group_by")]
245    fn unique(&self) -> PolarsResult<Series> {
246        let ca = NullChunked::new(self.name.clone(), self.n_unique().unwrap());
247        Ok(ca.into_series())
248    }
249
250    #[cfg(feature = "algorithm_group_by")]
251    fn n_unique(&self) -> PolarsResult<usize> {
252        let n = if self.is_empty() { 0 } else { 1 };
253        Ok(n)
254    }
255
256    #[cfg(feature = "algorithm_group_by")]
257    fn arg_unique(&self) -> PolarsResult<IdxCa> {
258        let idxs: Vec<IdxSize> = (0..self.n_unique().unwrap() as IdxSize).collect();
259        Ok(IdxCa::new(self.name().clone(), idxs))
260    }
261
262    fn new_from_index(&self, _index: usize, length: usize) -> Series {
263        NullChunked::new(self.name.clone(), length).into_series()
264    }
265
266    unsafe fn get_unchecked(&self, _index: usize) -> AnyValue<'_> {
267        AnyValue::Null
268    }
269
270    fn slice(&self, offset: i64, length: usize) -> Series {
271        let (chunks, len) = chunkops::slice(&self.chunks, offset, length, self.len());
272        NullChunked {
273            name: self.name.clone(),
274            length: len as IdxSize,
275            chunks,
276        }
277        .into_series()
278    }
279
280    fn split_at(&self, offset: i64) -> (Series, Series) {
281        let (l, r) = chunkops::split_at(self.chunks(), offset, self.len());
282        (
283            NullChunked {
284                name: self.name.clone(),
285                length: l.iter().map(|arr| arr.len() as IdxSize).sum(),
286                chunks: l,
287            }
288            .into_series(),
289            NullChunked {
290                name: self.name.clone(),
291                length: r.iter().map(|arr| arr.len() as IdxSize).sum(),
292                chunks: r,
293            }
294            .into_series(),
295        )
296    }
297
298    fn sort_with(&self, _options: SortOptions) -> PolarsResult<Series> {
299        Ok(self.clone().into_series())
300    }
301
302    fn arg_sort(&self, _options: SortOptions) -> IdxCa {
303        IdxCa::from_vec(self.name().clone(), (0..self.len() as IdxSize).collect())
304    }
305
306    fn is_null(&self) -> BooleanChunked {
307        BooleanChunked::full(self.name().clone(), true, self.len())
308    }
309
310    fn is_not_null(&self) -> BooleanChunked {
311        BooleanChunked::full(self.name().clone(), false, self.len())
312    }
313
314    fn reverse(&self) -> Series {
315        self.clone().into_series()
316    }
317
318    fn filter(&self, filter: &BooleanChunked) -> PolarsResult<Series> {
319        let len = if self.is_empty() {
320            // We still allow a length of `1` because it could be `lit(true)`.
321            polars_ensure!(filter.len() <= 1, ShapeMismatch: "filter's length: {} differs from that of the series: 0", filter.len());
322            0
323        } else if filter.len() == 1 {
324            return match filter.get(0) {
325                Some(true) => Ok(self.clone().into_series()),
326                None | Some(false) => Ok(NullChunked::new(self.name.clone(), 0).into_series()),
327            };
328        } else {
329            polars_ensure!(filter.len() == self.len(), ShapeMismatch: "filter's length: {} differs from that of the series: {}", filter.len(), self.len());
330            filter.sum().unwrap_or(0) as usize
331        };
332        Ok(NullChunked::new(self.name.clone(), len).into_series())
333    }
334
335    fn shift(&self, _periods: i64) -> Series {
336        self.clone().into_series()
337    }
338
339    fn sum_reduce(&self) -> PolarsResult<Scalar> {
340        Ok(Scalar::null(DataType::Null))
341    }
342
343    fn min_reduce(&self) -> PolarsResult<Scalar> {
344        Ok(Scalar::null(DataType::Null))
345    }
346
347    fn max_reduce(&self) -> PolarsResult<Scalar> {
348        Ok(Scalar::null(DataType::Null))
349    }
350
351    fn mean_reduce(&self) -> PolarsResult<Scalar> {
352        Ok(Scalar::null(DataType::Null))
353    }
354
355    fn median_reduce(&self) -> PolarsResult<Scalar> {
356        Ok(Scalar::null(DataType::Null))
357    }
358
359    fn std_reduce(&self, _ddof: u8) -> PolarsResult<Scalar> {
360        Ok(Scalar::null(DataType::Null))
361    }
362
363    fn var_reduce(&self, _ddof: u8) -> PolarsResult<Scalar> {
364        Ok(Scalar::null(DataType::Null))
365    }
366
367    fn append(&mut self, other: &Series) -> PolarsResult<()> {
368        polars_ensure!(other.dtype() == &DataType::Null, ComputeError: "expected null dtype");
369        // we don't create a new null array to keep probability of aligned chunks higher
370        self.length += other.len() as IdxSize;
371        self.chunks.extend(other.chunks().iter().cloned());
372        Ok(())
373    }
374    fn append_owned(&mut self, mut other: Series) -> PolarsResult<()> {
375        polars_ensure!(other.dtype() == &DataType::Null, ComputeError: "expected null dtype");
376        // we don't create a new null array to keep probability of aligned chunks higher
377        let other: &mut NullChunked = other._get_inner_mut().as_any_mut().downcast_mut().unwrap();
378        self.length += other.len() as IdxSize;
379        self.chunks.extend(std::mem::take(&mut other.chunks));
380        Ok(())
381    }
382
383    fn extend(&mut self, other: &Series) -> PolarsResult<()> {
384        *self = NullChunked::new(self.name.clone(), self.len() + other.len());
385        Ok(())
386    }
387
388    #[cfg(feature = "approx_unique")]
389    fn approx_n_unique(&self) -> PolarsResult<IdxSize> {
390        Ok(if self.is_empty() { 0 } else { 1 })
391    }
392
393    fn clone_inner(&self) -> Arc<dyn SeriesTrait> {
394        Arc::new(self.clone())
395    }
396
397    fn find_validity_mismatch(&self, other: &Series, idxs: &mut Vec<IdxSize>) {
398        ChunkNestingUtils::find_validity_mismatch(self, other, idxs)
399    }
400
401    fn as_any(&self) -> &dyn Any {
402        self
403    }
404
405    fn as_any_mut(&mut self) -> &mut dyn Any {
406        self
407    }
408
409    fn as_phys_any(&self) -> &dyn Any {
410        self
411    }
412
413    fn as_arc_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
414        self as _
415    }
416}
417
418unsafe impl IntoSeries for NullChunked {
419    fn into_series(self) -> Series
420    where
421        Self: Sized,
422    {
423        Series(Arc::new(self))
424    }
425}