Path: blob/main/crates/polars-ops/src/series/ops/various.rs
8446 views
use num_traits::Bounded;1#[cfg(feature = "dtype-struct")]2use polars_core::chunked_array::ops::row_encode::_get_rows_encoded_ca;3use polars_core::prelude::arity::unary_elementwise_values;4use polars_core::prelude::*;5use polars_core::series::IsSorted;6use polars_core::with_match_physical_numeric_polars_type;7#[cfg(feature = "hash")]8use polars_utils::aliases::PlSeedableRandomStateQuality;9use polars_utils::total_ord::TotalOrd;1011use crate::series::ops::SeriesSealed;1213pub trait SeriesMethods: SeriesSealed {14/// Create a [`DataFrame`] with the unique `values` of this [`Series`] and a column `"counts"`15/// with dtype [`IdxType`]16fn value_counts(17&self,18sort: bool,19parallel: bool,20name: PlSmallStr,21normalize: bool,22) -> PolarsResult<DataFrame> {23let s = self.as_series();24polars_ensure!(25s.name() != &name,26Duplicate: "using `value_counts` on a column/series named '{}' would lead to duplicate \27column names; change `name` to fix", name,28);29// we need to sort here as well in case of `maintain_order` because duplicates behavior is undefined30let groups = s.group_tuples(parallel, sort)?;31let values = unsafe { s.agg_first(&groups) }32.with_name(s.name().clone())33.into();34let counts = groups.group_count().with_name(name.clone());3536let counts = if normalize {37let len = s.len() as f64;38let counts: Float64Chunked =39unary_elementwise_values(&counts, |count| count as f64 / len);40counts.into_column()41} else {42counts.into_column()43};4445let height = counts.len();46let cols = vec![values, counts];47let df = unsafe { DataFrame::new_unchecked(height, cols) };48if sort {49df.sort(50[name],51SortMultipleOptions::default()52.with_order_descending(true)53.with_multithreaded(parallel),54)55} else {56Ok(df)57}58}5960#[cfg(feature = "hash")]61fn hash(&self, build_hasher: PlSeedableRandomStateQuality) -> UInt64Chunked {62let s = self.as_series();63let mut h = vec![];64s.0.vec_hash(build_hasher, &mut h).unwrap();65UInt64Chunked::from_vec(s.name().clone(), h)66}6768fn ensure_sorted_arg(&self, operation: &str) -> PolarsResult<()> {69polars_ensure!(self.is_sorted(Default::default())?, InvalidOperation: "argument in operation '{}' is not sorted, please sort the 'expr/series/column' first", operation);70Ok(())71}7273/// Checks if a [`Series`] is sorted. Tries to fail fast.74fn is_sorted(&self, options: SortOptions) -> PolarsResult<bool> {75let s = self.as_series();76let null_count = s.null_count();7778// fast paths79if (options.descending80&& (options.nulls_last || null_count == 0)81&& matches!(s.is_sorted_flag(), IsSorted::Descending))82|| (!options.descending83&& (!options.nulls_last || null_count == 0)84&& matches!(s.is_sorted_flag(), IsSorted::Ascending))85{86return Ok(true);87}8889// for struct types we row-encode and recurse90#[cfg(feature = "dtype-struct")]91if matches!(s.dtype(), DataType::Struct(_)) {92let encoded = _get_rows_encoded_ca(93PlSmallStr::EMPTY,94&[s.clone().into()],95&[options.descending],96&[options.nulls_last],97false,98)?;99return encoded.into_series().is_sorted(options);100}101102let s_len = s.len();103if null_count == s_len {104// All nulls is all equal105return Ok(true);106}107// Check if nulls are in the right location.108if null_count > 0 {109// The slice triggers a fast null count110if options.nulls_last {111if s.slice((s_len - null_count) as i64, null_count)112.null_count()113!= null_count114{115return Ok(false);116}117} else if s.slice(0, null_count).null_count() != null_count {118return Ok(false);119}120}121122if s.dtype().is_primitive_numeric() {123with_match_physical_numeric_polars_type!(s.dtype(), |$T| {124let ca: &ChunkedArray<$T> = s.as_ref().as_ref().as_ref();125return Ok(is_sorted_ca_num::<$T>(ca, options))126})127}128129let cmp_len = s_len - null_count - 1; // Number of comparisons we might have to do130// TODO! Change this, allocation of a full boolean series is too expensive and doesn't fail fast.131// Compare adjacent elements with no-copy slices that don't include any nulls132let offset = !options.nulls_last as i64 * null_count as i64;133let (s1, s2) = (s.slice(offset, cmp_len), s.slice(offset + 1, cmp_len));134let cmp_op = if options.descending {135Series::gt_eq136} else {137Series::lt_eq138};139Ok(cmp_op(&s1, &s2)?.all())140}141}142143fn check_cmp<T: NumericNative, Cmp: Fn(&T, &T) -> bool>(144vals: &[T],145f: Cmp,146previous: &mut T,147) -> bool {148let mut sorted = true;149150// Outer loop so we can fail fast151// Inner loop will auto vectorize152for c in vals.chunks(1024) {153// don't early stop or branch154// so it autovectorizes155for v in c {156sorted &= f(previous, v);157*previous = *v;158}159if !sorted {160return false;161}162}163sorted164}165166// Assumes nulls last/first is already checked.167fn is_sorted_ca_num<T: PolarsNumericType>(ca: &ChunkedArray<T>, options: SortOptions) -> bool {168if let Ok(vals) = ca.cont_slice() {169let mut previous = vals[0];170return if options.descending {171check_cmp(vals, |prev, c| prev.tot_ge(c), &mut previous)172} else {173check_cmp(vals, |prev, c| prev.tot_le(c), &mut previous)174};175};176177if ca.null_count() == 0 {178let mut previous = if options.descending {179T::Native::max_value()180} else {181T::Native::min_value()182};183for arr in ca.downcast_iter() {184let vals = arr.values();185186let sorted = if options.descending {187check_cmp(vals, |prev, c| prev.tot_ge(c), &mut previous)188} else {189check_cmp(vals, |prev, c| prev.tot_le(c), &mut previous)190};191if !sorted {192return false;193}194}195return true;196};197198// Slice off nulls and recurse.199let null_count = ca.null_count();200if options.nulls_last {201let ca = ca.slice(0, ca.len() - null_count);202is_sorted_ca_num(&ca, options)203} else {204let ca = ca.slice(null_count as i64, ca.len() - null_count);205is_sorted_ca_num(&ca, options)206}207}208209impl SeriesMethods for Series {}210211212