Path: blob/main/crates/polars-core/src/series/implementations/null.rs
6940 views
use std::any::Any;12use polars_error::constants::LENGTH_LIMIT_MSG;34use self::compare_inner::TotalOrdInner;5use super::*;6use crate::chunked_array::ops::compare_inner::{IntoTotalEqInner, NonNull, TotalEqInner};7use crate::chunked_array::ops::sort::arg_sort_multiple::arg_sort_multiple_impl;8use crate::prelude::*;9use crate::series::private::{PrivateSeries, PrivateSeriesNumeric};10use crate::series::*;1112impl Series {13pub fn new_null(name: PlSmallStr, len: usize) -> Series {14NullChunked::new(name, len).into_series()15}16}1718#[derive(Clone)]19pub struct NullChunked {20pub(crate) name: PlSmallStr,21length: IdxSize,22// we still need chunks as many series consumers expect23// chunks to be there24chunks: Vec<ArrayRef>,25}2627impl NullChunked {28pub(crate) fn new(name: PlSmallStr, len: usize) -> Self {29Self {30name,31length: len as IdxSize,32chunks: vec![Box::new(arrow::array::NullArray::new(33ArrowDataType::Null,34len,35))],36}37}3839pub fn len(&self) -> usize {40self.length as usize41}4243pub fn is_empty(&self) -> bool {44self.length == 045}46}47impl PrivateSeriesNumeric for NullChunked {48fn bit_repr(&self) -> Option<BitRepr> {49Some(BitRepr::U32(UInt32Chunked::full_null(50self.name.clone(),51self.len(),52)))53}54}5556impl PrivateSeries for NullChunked {57fn compute_len(&mut self) {58fn inner(chunks: &[ArrayRef]) -> usize {59match chunks.len() {60// fast path611 => chunks[0].len(),62_ => chunks.iter().fold(0, |acc, arr| acc + arr.len()),63}64}65self.length = IdxSize::try_from(inner(&self.chunks)).expect(LENGTH_LIMIT_MSG);66}67fn _field(&self) -> Cow<'_, Field> {68Cow::Owned(Field::new(self.name().clone(), DataType::Null))69}7071#[allow(unused)]72fn _set_flags(&mut self, flags: StatisticsFlags) {}7374fn _dtype(&self) -> &DataType {75&DataType::Null76}7778#[cfg(feature = "zip_with")]79fn zip_with_same_type(&self, mask: &BooleanChunked, other: &Series) -> PolarsResult<Series> {80let len = match (self.len(), mask.len(), other.len()) {81(a, b, c) if a == b && b == c => a,82(1, a, b) | (a, 1, b) | (a, b, 1) if a == b => a,83(a, 1, 1) | (1, a, 1) | (1, 1, a) => a,84(_, 0, _) => 0,85_ => {86polars_bail!(ShapeMismatch: "shapes of `self`, `mask` and `other` are not suitable for `zip_with` operation")87},88};8990Ok(Self::new(self.name().clone(), len).into_series())91}9293fn into_total_eq_inner<'a>(&'a self) -> Box<dyn TotalEqInner + 'a> {94IntoTotalEqInner::into_total_eq_inner(self)95}96fn into_total_ord_inner<'a>(&'a self) -> Box<dyn TotalOrdInner + 'a> {97IntoTotalOrdInner::into_total_ord_inner(self)98}99100fn subtract(&self, _rhs: &Series) -> PolarsResult<Series> {101null_arithmetic(self, _rhs, "subtract")102}103104fn add_to(&self, _rhs: &Series) -> PolarsResult<Series> {105null_arithmetic(self, _rhs, "add_to")106}107fn multiply(&self, _rhs: &Series) -> PolarsResult<Series> {108null_arithmetic(self, _rhs, "multiply")109}110fn divide(&self, _rhs: &Series) -> PolarsResult<Series> {111null_arithmetic(self, _rhs, "divide")112}113fn remainder(&self, _rhs: &Series) -> PolarsResult<Series> {114null_arithmetic(self, _rhs, "remainder")115}116117#[cfg(feature = "algorithm_group_by")]118fn group_tuples(&self, _multithreaded: bool, _sorted: bool) -> PolarsResult<GroupsType> {119Ok(if self.is_empty() {120GroupsType::default()121} else {122GroupsType::Slice {123groups: vec![[0, self.length]],124rolling: false,125}126})127}128129#[cfg(feature = "algorithm_group_by")]130unsafe fn agg_list(&self, groups: &GroupsType) -> Series {131AggList::agg_list(self, groups)132}133134fn _get_flags(&self) -> StatisticsFlags {135StatisticsFlags::empty()136}137138fn vec_hash(139&self,140random_state: PlSeedableRandomStateQuality,141buf: &mut Vec<u64>,142) -> PolarsResult<()> {143VecHash::vec_hash(self, random_state, buf)?;144Ok(())145}146147fn vec_hash_combine(148&self,149build_hasher: PlSeedableRandomStateQuality,150hashes: &mut [u64],151) -> PolarsResult<()> {152VecHash::vec_hash_combine(self, build_hasher, hashes)?;153Ok(())154}155156fn arg_sort_multiple(157&self,158by: &[Column],159options: &SortMultipleOptions,160) -> PolarsResult<IdxCa> {161let vals = (0..self.len())162.map(|i| (i as IdxSize, NonNull(())))163.collect();164arg_sort_multiple_impl(vals, by, options)165}166}167168fn null_arithmetic(lhs: &NullChunked, rhs: &Series, op: &str) -> PolarsResult<Series> {169let output_len = match (lhs.len(), rhs.len()) {170(1, len_r) => len_r,171(len_l, 1) => len_l,172(len_l, len_r) if len_l == len_r => len_l,173_ => polars_bail!(ComputeError: "Cannot {:?} two series of different lengths.", op),174};175Ok(NullChunked::new(lhs.name().clone(), output_len).into_series())176}177178impl SeriesTrait for NullChunked {179fn name(&self) -> &PlSmallStr {180&self.name181}182183fn rename(&mut self, name: PlSmallStr) {184self.name = name185}186187fn chunks(&self) -> &Vec<ArrayRef> {188&self.chunks189}190unsafe fn chunks_mut(&mut self) -> &mut Vec<ArrayRef> {191&mut self.chunks192}193194fn chunk_lengths(&self) -> ChunkLenIter<'_> {195self.chunks.iter().map(|chunk| chunk.len())196}197198fn take(&self, indices: &IdxCa) -> PolarsResult<Series> {199Ok(NullChunked::new(self.name.clone(), indices.len()).into_series())200}201202unsafe fn take_unchecked(&self, indices: &IdxCa) -> Series {203NullChunked::new(self.name.clone(), indices.len()).into_series()204}205206fn take_slice(&self, indices: &[IdxSize]) -> PolarsResult<Series> {207Ok(NullChunked::new(self.name.clone(), indices.len()).into_series())208}209210unsafe fn take_slice_unchecked(&self, indices: &[IdxSize]) -> Series {211NullChunked::new(self.name.clone(), indices.len()).into_series()212}213214fn len(&self) -> usize {215self.length as usize216}217218fn has_nulls(&self) -> bool {219!self.is_empty()220}221222fn rechunk(&self) -> Series {223NullChunked::new(self.name.clone(), self.len()).into_series()224}225226fn drop_nulls(&self) -> Series {227NullChunked::new(self.name.clone(), 0).into_series()228}229230fn cast(&self, dtype: &DataType, _cast_options: CastOptions) -> PolarsResult<Series> {231Ok(Series::full_null(self.name.clone(), self.len(), dtype))232}233234fn null_count(&self) -> usize {235self.len()236}237238#[cfg(feature = "algorithm_group_by")]239fn unique(&self) -> PolarsResult<Series> {240let ca = NullChunked::new(self.name.clone(), self.n_unique().unwrap());241Ok(ca.into_series())242}243244#[cfg(feature = "algorithm_group_by")]245fn n_unique(&self) -> PolarsResult<usize> {246let n = if self.is_empty() { 0 } else { 1 };247Ok(n)248}249250#[cfg(feature = "algorithm_group_by")]251fn arg_unique(&self) -> PolarsResult<IdxCa> {252let idxs: Vec<IdxSize> = (0..self.n_unique().unwrap() as IdxSize).collect();253Ok(IdxCa::new(self.name().clone(), idxs))254}255256fn new_from_index(&self, _index: usize, length: usize) -> Series {257NullChunked::new(self.name.clone(), length).into_series()258}259260unsafe fn get_unchecked(&self, _index: usize) -> AnyValue<'_> {261AnyValue::Null262}263264fn slice(&self, offset: i64, length: usize) -> Series {265let (chunks, len) = chunkops::slice(&self.chunks, offset, length, self.len());266NullChunked {267name: self.name.clone(),268length: len as IdxSize,269chunks,270}271.into_series()272}273274fn split_at(&self, offset: i64) -> (Series, Series) {275let (l, r) = chunkops::split_at(self.chunks(), offset, self.len());276(277NullChunked {278name: self.name.clone(),279length: l.iter().map(|arr| arr.len() as IdxSize).sum(),280chunks: l,281}282.into_series(),283NullChunked {284name: self.name.clone(),285length: r.iter().map(|arr| arr.len() as IdxSize).sum(),286chunks: r,287}288.into_series(),289)290}291292fn sort_with(&self, _options: SortOptions) -> PolarsResult<Series> {293Ok(self.clone().into_series())294}295296fn arg_sort(&self, _options: SortOptions) -> IdxCa {297IdxCa::from_vec(self.name().clone(), (0..self.len() as IdxSize).collect())298}299300fn is_null(&self) -> BooleanChunked {301BooleanChunked::full(self.name().clone(), true, self.len())302}303304fn is_not_null(&self) -> BooleanChunked {305BooleanChunked::full(self.name().clone(), false, self.len())306}307308fn reverse(&self) -> Series {309self.clone().into_series()310}311312fn filter(&self, filter: &BooleanChunked) -> PolarsResult<Series> {313let len = if self.is_empty() {314// We still allow a length of `1` because it could be `lit(true)`.315polars_ensure!(filter.len() <= 1, ShapeMismatch: "filter's length: {} differs from that of the series: 0", filter.len());3160317} else if filter.len() == 1 {318return match filter.get(0) {319Some(true) => Ok(self.clone().into_series()),320None | Some(false) => Ok(NullChunked::new(self.name.clone(), 0).into_series()),321};322} else {323polars_ensure!(filter.len() == self.len(), ShapeMismatch: "filter's length: {} differs from that of the series: {}", filter.len(), self.len());324filter.sum().unwrap_or(0) as usize325};326Ok(NullChunked::new(self.name.clone(), len).into_series())327}328329fn shift(&self, _periods: i64) -> Series {330self.clone().into_series()331}332333fn append(&mut self, other: &Series) -> PolarsResult<()> {334polars_ensure!(other.dtype() == &DataType::Null, ComputeError: "expected null dtype");335// we don't create a new null array to keep probability of aligned chunks higher336self.length += other.len() as IdxSize;337self.chunks.extend(other.chunks().iter().cloned());338Ok(())339}340fn append_owned(&mut self, mut other: Series) -> PolarsResult<()> {341polars_ensure!(other.dtype() == &DataType::Null, ComputeError: "expected null dtype");342// we don't create a new null array to keep probability of aligned chunks higher343let other: &mut NullChunked = other._get_inner_mut().as_any_mut().downcast_mut().unwrap();344self.length += other.len() as IdxSize;345self.chunks.extend(std::mem::take(&mut other.chunks));346Ok(())347}348349fn extend(&mut self, other: &Series) -> PolarsResult<()> {350*self = NullChunked::new(self.name.clone(), self.len() + other.len());351Ok(())352}353354fn clone_inner(&self) -> Arc<dyn SeriesTrait> {355Arc::new(self.clone())356}357358fn find_validity_mismatch(&self, other: &Series, idxs: &mut Vec<IdxSize>) {359ChunkNestingUtils::find_validity_mismatch(self, other, idxs)360}361362fn as_any(&self) -> &dyn Any {363self364}365366fn as_any_mut(&mut self) -> &mut dyn Any {367self368}369370fn as_phys_any(&self) -> &dyn Any {371self372}373374fn as_arc_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {375self as _376}377}378379unsafe impl IntoSeries for NullChunked {380fn into_series(self) -> Series381where382Self: Sized,383{384Series(Arc::new(self))385}386}387388389