1use std::fmt::{Debug, Display, Formatter};
2use std::hash::Hash;
3
4use num_traits::NumCast;
5use polars_compute::rolling::QuantileMethod;
6use polars_utils::format_pl_smallstr;
7use polars_utils::hashing::DirtyHash;
8use rayon::prelude::*;
9
10use self::hashing::*;
11use crate::POOL;
12use crate::prelude::*;
13use crate::utils::{_set_partition_size, accumulate_dataframes_vertical};
14
15pub mod aggregations;
16pub(crate) mod hashing;
17mod into_groups;
18mod position;
19
20pub use into_groups::*;
21pub use position::*;
22
23use crate::chunked_array::ops::row_encode::{
24 encode_rows_unordered, encode_rows_vertical_par_unordered,
25};
26
27impl DataFrame {
28 pub fn group_by_with_series(
29 &self,
30 mut by: Vec<Column>,
31 multithreaded: bool,
32 sorted: bool,
33 ) -> PolarsResult<GroupBy<'_>> {
34 polars_ensure!(
35 !by.is_empty(),
36 ComputeError: "at least one key is required in a group_by operation"
37 );
38
39 let common_height = if self.width() > 0 {
43 self.height()
44 } else {
45 by.iter().map(|s| s.len()).max().expect("at least 1 key")
46 };
47 for by_key in by.iter_mut() {
48 if by_key.len() != common_height {
49 polars_ensure!(
50 by_key.len() == 1,
51 ShapeMismatch: "series used as keys should have the same length as the DataFrame"
52 );
53 *by_key = by_key.new_from_index(0, common_height)
54 }
55 }
56
57 let groups = if by.len() == 1 {
58 let column = &by[0];
59 column
60 .as_materialized_series()
61 .group_tuples(multithreaded, sorted)
62 } else if by.iter().any(|s| s.dtype().is_object()) {
63 #[cfg(feature = "object")]
64 {
65 let mut df = DataFrame::new(self.height(), by.clone()).unwrap();
66 let n = df.height();
67 let rows = df.to_av_rows();
68 let iter = (0..n).map(|i| rows.get(i));
69 Ok(group_by(iter, sorted))
70 }
71 #[cfg(not(feature = "object"))]
72 {
73 unreachable!()
74 }
75 } else {
76 let by = by
78 .iter()
79 .filter(|s| !s.dtype().is_null())
80 .cloned()
81 .collect::<Vec<_>>();
82 if by.is_empty() {
83 let groups = if self.height() == 0 {
84 vec![]
85 } else {
86 vec![[0, self.height() as IdxSize]]
87 };
88
89 Ok(GroupsType::new_slice(groups, false, true))
90 } else {
91 let rows = if multithreaded {
92 encode_rows_vertical_par_unordered(&by)
93 } else {
94 encode_rows_unordered(&by)
95 }?
96 .into_series();
97 rows.group_tuples(multithreaded, sorted)
98 }
99 };
100 Ok(GroupBy::new(self, by, groups?.into_sliceable(), None))
101 }
102
103 pub fn group_by<I, S>(&self, by: I) -> PolarsResult<GroupBy<'_>>
116 where
117 I: IntoIterator<Item = S>,
118 S: AsRef<str>,
119 {
120 let selected_keys = self.select_to_vec(by)?;
121 self.group_by_with_series(selected_keys, true, false)
122 }
123
124 pub fn group_by_stable<I, S>(&self, by: I) -> PolarsResult<GroupBy<'_>>
127 where
128 I: IntoIterator<Item = S>,
129 S: AsRef<str>,
130 {
131 let selected_keys = self.select_to_vec(by)?;
132 self.group_by_with_series(selected_keys, true, true)
133 }
134}
135
136#[derive(Debug, Clone)]
186pub struct GroupBy<'a> {
187 pub df: &'a DataFrame,
188 pub(crate) selected_keys: Vec<Column>,
189 groups: GroupPositions,
191 pub(crate) selected_agg: Option<Vec<PlSmallStr>>,
193}
194
195impl<'a> GroupBy<'a> {
196 pub fn new(
197 df: &'a DataFrame,
198 by: Vec<Column>,
199 groups: GroupPositions,
200 selected_agg: Option<Vec<PlSmallStr>>,
201 ) -> Self {
202 GroupBy {
203 df,
204 selected_keys: by,
205 groups,
206 selected_agg,
207 }
208 }
209
210 #[must_use]
216 pub fn select<I: IntoIterator<Item = S>, S: Into<PlSmallStr>>(mut self, selection: I) -> Self {
217 self.selected_agg = Some(selection.into_iter().map(|s| s.into()).collect());
218 self
219 }
220
221 pub fn get_groups(&self) -> &GroupPositions {
226 &self.groups
227 }
228
229 pub unsafe fn get_groups_mut(&mut self) -> &mut GroupPositions {
238 &mut self.groups
239 }
240
241 pub fn into_groups(self) -> GroupPositions {
242 self.groups
243 }
244
245 pub fn keys_sliced(&self, slice: Option<(i64, usize)>) -> Vec<Column> {
246 #[allow(unused_assignments)]
247 let mut groups_owned = None;
249
250 let groups = if let Some((offset, len)) = slice {
251 groups_owned = Some(self.groups.slice(offset, len));
252 groups_owned.as_deref().unwrap()
253 } else {
254 &self.groups
255 };
256 POOL.install(|| {
257 self.selected_keys
258 .par_iter()
259 .map(Column::as_materialized_series)
260 .map(|s| {
261 match groups {
262 GroupsType::Idx(groups) => {
263 let mut out = unsafe { s.take_slice_unchecked(groups.first()) };
265 if groups.sorted {
266 out.set_sorted_flag(s.is_sorted_flag());
267 };
268 out
269 },
270 GroupsType::Slice {
271 groups,
272 overlapping,
273 monotonic: _,
274 } => {
275 if *overlapping && !groups.is_empty() {
276 let offset = groups[0][0];
278 let [upper_offset, upper_len] = groups[groups.len() - 1];
279 return s.slice(
280 offset as i64,
281 ((upper_offset + upper_len) - offset) as usize,
282 );
283 }
284
285 let indices = groups
286 .iter()
287 .map(|&[first, _len]| first)
288 .collect_ca(PlSmallStr::EMPTY);
289 let mut out = unsafe { s.take_unchecked(&indices) };
291 out.set_sorted_flag(s.is_sorted_flag());
293 out
294 },
295 }
296 })
297 .map(Column::from)
298 .collect()
299 })
300 }
301
302 pub fn keys(&self) -> Vec<Column> {
303 self.keys_sliced(None)
304 }
305
306 fn prepare_agg(&self) -> PolarsResult<(Vec<Column>, Vec<Column>)> {
307 let keys = self.keys();
308
309 let agg_col = match &self.selected_agg {
310 Some(selection) => self.df.select_to_vec(selection),
311 None => {
312 let by: Vec<_> = self.selected_keys.iter().map(|s| s.name()).collect();
313 let selection = self
314 .df
315 .columns()
316 .iter()
317 .map(|s| s.name())
318 .filter(|a| !by.contains(a))
319 .cloned()
320 .collect::<Vec<_>>();
321
322 self.df.select_to_vec(selection.as_slice())
323 },
324 }?;
325
326 Ok((keys, agg_col))
327 }
328
329 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
355 pub fn mean(&self) -> PolarsResult<DataFrame> {
356 let (mut cols, agg_cols) = self.prepare_agg()?;
357
358 for agg_col in agg_cols {
359 let new_name = fmt_group_by_column(agg_col.name().as_str(), GroupByMethod::Mean);
360 let mut agg = unsafe { agg_col.agg_mean(&self.groups) };
361 agg.rename(new_name);
362 cols.push(agg);
363 }
364
365 DataFrame::new_infer_height(cols)
366 }
367
368 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
394 pub fn sum(&self) -> PolarsResult<DataFrame> {
395 let (mut cols, agg_cols) = self.prepare_agg()?;
396
397 for agg_col in agg_cols {
398 let new_name = fmt_group_by_column(agg_col.name().as_str(), GroupByMethod::Sum);
399 let mut agg = unsafe { agg_col.agg_sum(&self.groups) };
400 agg.rename(new_name);
401 cols.push(agg);
402 }
403 DataFrame::new_infer_height(cols)
404 }
405
406 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
432 pub fn min(&self) -> PolarsResult<DataFrame> {
433 let (mut cols, agg_cols) = self.prepare_agg()?;
434 for agg_col in agg_cols {
435 let new_name = fmt_group_by_column(agg_col.name().as_str(), GroupByMethod::Min);
436 let mut agg = unsafe { agg_col.agg_min(&self.groups) };
437 agg.rename(new_name);
438 cols.push(agg);
439 }
440 DataFrame::new_infer_height(cols)
441 }
442
443 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
469 pub fn max(&self) -> PolarsResult<DataFrame> {
470 let (mut cols, agg_cols) = self.prepare_agg()?;
471 for agg_col in agg_cols {
472 let new_name = fmt_group_by_column(agg_col.name().as_str(), GroupByMethod::Max);
473 let mut agg = unsafe { agg_col.agg_max(&self.groups) };
474 agg.rename(new_name);
475 cols.push(agg);
476 }
477 DataFrame::new_infer_height(cols)
478 }
479
480 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
506 pub fn first(&self) -> PolarsResult<DataFrame> {
507 let (mut cols, agg_cols) = self.prepare_agg()?;
508 for agg_col in agg_cols {
509 let new_name = fmt_group_by_column(agg_col.name().as_str(), GroupByMethod::First);
510 let mut agg = unsafe { agg_col.agg_first(&self.groups) };
511 agg.rename(new_name);
512 cols.push(agg);
513 }
514 DataFrame::new_infer_height(cols)
515 }
516
517 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
543 pub fn last(&self) -> PolarsResult<DataFrame> {
544 let (mut cols, agg_cols) = self.prepare_agg()?;
545 for agg_col in agg_cols {
546 let new_name = fmt_group_by_column(agg_col.name().as_str(), GroupByMethod::Last);
547 let mut agg = unsafe { agg_col.agg_last(&self.groups) };
548 agg.rename(new_name);
549 cols.push(agg);
550 }
551 DataFrame::new_infer_height(cols)
552 }
553
554 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
580 pub fn n_unique(&self) -> PolarsResult<DataFrame> {
581 let (mut cols, agg_cols) = self.prepare_agg()?;
582 for agg_col in agg_cols {
583 let new_name = fmt_group_by_column(agg_col.name().as_str(), GroupByMethod::NUnique);
584 let mut agg = unsafe { agg_col.agg_n_unique(&self.groups) };
585 agg.rename(new_name);
586 cols.push(agg);
587 }
588 DataFrame::new_infer_height(cols)
589 }
590
591 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
603 pub fn quantile(&self, quantile: f64, method: QuantileMethod) -> PolarsResult<DataFrame> {
604 polars_ensure!(
605 (0.0..=1.0).contains(&quantile),
606 ComputeError: "`quantile` should be within 0.0 and 1.0"
607 );
608 let (mut cols, agg_cols) = self.prepare_agg()?;
609 for agg_col in agg_cols {
610 let new_name = fmt_group_by_column(
611 agg_col.name().as_str(),
612 GroupByMethod::Quantile(quantile, method),
613 );
614 let mut agg = unsafe { agg_col.agg_quantile(&self.groups, quantile, method) };
615 agg.rename(new_name);
616 cols.push(agg);
617 }
618 DataFrame::new_infer_height(cols)
619 }
620
621 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
632 pub fn median(&self) -> PolarsResult<DataFrame> {
633 let (mut cols, agg_cols) = self.prepare_agg()?;
634 for agg_col in agg_cols {
635 let new_name = fmt_group_by_column(agg_col.name().as_str(), GroupByMethod::Median);
636 let mut agg = unsafe { agg_col.agg_median(&self.groups) };
637 agg.rename(new_name);
638 cols.push(agg);
639 }
640 DataFrame::new_infer_height(cols)
641 }
642
643 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
645 pub fn var(&self, ddof: u8) -> PolarsResult<DataFrame> {
646 let (mut cols, agg_cols) = self.prepare_agg()?;
647 for agg_col in agg_cols {
648 let new_name = fmt_group_by_column(agg_col.name().as_str(), GroupByMethod::Var(ddof));
649 let mut agg = unsafe { agg_col.agg_var(&self.groups, ddof) };
650 agg.rename(new_name);
651 cols.push(agg);
652 }
653 DataFrame::new_infer_height(cols)
654 }
655
656 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
658 pub fn std(&self, ddof: u8) -> PolarsResult<DataFrame> {
659 let (mut cols, agg_cols) = self.prepare_agg()?;
660 for agg_col in agg_cols {
661 let new_name = fmt_group_by_column(agg_col.name().as_str(), GroupByMethod::Std(ddof));
662 let mut agg = unsafe { agg_col.agg_std(&self.groups, ddof) };
663 agg.rename(new_name);
664 cols.push(agg);
665 }
666 DataFrame::new_infer_height(cols)
667 }
668
669 pub fn count(&self) -> PolarsResult<DataFrame> {
695 let (mut cols, agg_cols) = self.prepare_agg()?;
696
697 for agg_col in agg_cols {
698 let new_name = fmt_group_by_column(
699 agg_col.name().as_str(),
700 GroupByMethod::Count {
701 include_nulls: true,
702 },
703 );
704 let mut ca = self.groups.group_count();
705 ca.rename(new_name);
706 cols.push(ca.into_column());
707 }
708 DataFrame::new_infer_height(cols)
709 }
710
711 pub fn groups(&self) -> PolarsResult<DataFrame> {
737 let mut cols = self.keys();
738 let mut column = self.groups.as_list_chunked();
739 let new_name = fmt_group_by_column("", GroupByMethod::Groups);
740 column.rename(new_name);
741 cols.push(column.into_column());
742 DataFrame::new_infer_height(cols)
743 }
744
745 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
772 pub fn agg_list(&self) -> PolarsResult<DataFrame> {
773 let (mut cols, agg_cols) = self.prepare_agg()?;
774 for agg_col in agg_cols {
775 let new_name = fmt_group_by_column(agg_col.name().as_str(), GroupByMethod::Implode);
776 let mut agg = unsafe { agg_col.agg_list(&self.groups) };
777 agg.rename(new_name);
778 cols.push(agg);
779 }
780 DataFrame::new_infer_height(cols)
781 }
782
783 fn prepare_apply(&self) -> PolarsResult<DataFrame> {
784 if let Some(agg) = &self.selected_agg {
785 if agg.is_empty() {
786 Ok(self.df.clone())
787 } else {
788 let mut new_cols = Vec::with_capacity(self.selected_keys.len() + agg.len());
789 new_cols.extend_from_slice(&self.selected_keys);
790 let cols = self.df.select_to_vec(agg.as_slice())?;
791 new_cols.extend(cols);
792 Ok(unsafe { DataFrame::new_unchecked(self.df.height(), new_cols) })
793 }
794 } else {
795 Ok(self.df.clone())
796 }
797 }
798
799 #[deprecated(since = "0.24.1", note = "use polars.lazy aggregations")]
801 pub fn par_apply<F>(&self, f: F) -> PolarsResult<DataFrame>
802 where
803 F: Fn(DataFrame) -> PolarsResult<DataFrame> + Send + Sync,
804 {
805 polars_ensure!(self.df.height() > 0, ComputeError: "cannot group_by + apply on empty 'DataFrame'");
806 let df = self.prepare_apply()?;
807 let dfs = self
808 .get_groups()
809 .par_iter()
810 .map(|g| {
811 let sub_df = unsafe { take_df(&df, g) };
814 f(sub_df)
815 })
816 .collect::<PolarsResult<Vec<_>>>()?;
817
818 let mut df = accumulate_dataframes_vertical(dfs)?;
819 df.rechunk_mut_par();
820 Ok(df)
821 }
822
823 pub fn apply<F>(&self, f: F) -> PolarsResult<DataFrame>
825 where
826 F: FnMut(DataFrame) -> PolarsResult<DataFrame> + Send + Sync,
827 {
828 self.apply_sliced(None, f, None)
829 }
830
831 pub fn apply_sliced<F>(
832 &self,
833 slice: Option<(i64, usize)>,
834 mut f: F,
835 schema: Option<&SchemaRef>,
836 ) -> PolarsResult<DataFrame>
837 where
838 F: FnMut(DataFrame) -> PolarsResult<DataFrame> + Send + Sync,
839 {
840 if self.df.height() == 0 {
841 if let Some(schema) = schema {
843 return Ok(DataFrame::empty_with_arc_schema(schema.clone()));
844 }
845
846 polars_bail!(ComputeError: "cannot group_by + apply on empty 'DataFrame'");
847 }
848
849 let df = self.prepare_apply()?;
850 let max_height = if let Some((offset, len)) = slice {
851 offset.try_into().unwrap_or(usize::MAX).saturating_add(len)
852 } else {
853 usize::MAX
854 };
855 let mut height = 0;
856 let mut dfs = Vec::with_capacity(self.get_groups().len());
857 for g in self.get_groups().iter() {
858 let sub_df = unsafe { take_df(&df, g) };
860 let df = f(sub_df)?;
861 height += df.height();
862 dfs.push(df);
863
864 if height >= max_height {
867 break;
868 }
869 }
870
871 let mut df = accumulate_dataframes_vertical(dfs)?;
872 if let Some((offset, len)) = slice {
873 df = df.slice(offset, len);
874 }
875 Ok(df)
876 }
877
878 pub fn sliced(mut self, slice: Option<(i64, usize)>) -> Self {
879 match slice {
880 None => self,
881 Some((offset, length)) => {
882 self.groups = self.groups.slice(offset, length);
883 self.selected_keys = self.keys_sliced(slice);
884 self
885 },
886 }
887 }
888}
889
890unsafe fn take_df(df: &DataFrame, g: GroupsIndicator) -> DataFrame {
891 match g {
892 GroupsIndicator::Idx(idx) => df.take_slice_unchecked(idx.1),
893 GroupsIndicator::Slice([first, len]) => df.slice(first as i64, len as usize),
894 }
895}
896
897#[derive(Copy, Clone, Debug)]
898pub enum GroupByMethod {
899 Min,
900 NanMin,
901 Max,
902 NanMax,
903 Median,
904 Mean,
905 First,
906 FirstNonNull,
907 Last,
908 LastNonNull,
909 Item { allow_empty: bool },
910 Sum,
911 Groups,
912 NUnique,
913 Quantile(f64, QuantileMethod),
914 Count { include_nulls: bool },
915 Implode,
916 Std(u8),
917 Var(u8),
918 ArgMin,
919 ArgMax,
920}
921
922impl Display for GroupByMethod {
923 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
924 use GroupByMethod::*;
925 let s = match self {
926 Min => "min",
927 NanMin => "nan_min",
928 Max => "max",
929 NanMax => "nan_max",
930 Median => "median",
931 Mean => "mean",
932 First => "first",
933 FirstNonNull => "first_non_null",
934 Last => "last",
935 LastNonNull => "last_non_null",
936 Item { .. } => "item",
937 Sum => "sum",
938 Groups => "groups",
939 NUnique => "n_unique",
940 Quantile(_, _) => "quantile",
941 Count { .. } => "count",
942 Implode => "list",
943 Std(_) => "std",
944 Var(_) => "var",
945 ArgMin => "arg_min",
946 ArgMax => "arg_max",
947 };
948 write!(f, "{s}")
949 }
950}
951
952pub fn fmt_group_by_column(name: &str, method: GroupByMethod) -> PlSmallStr {
954 use GroupByMethod::*;
955 match method {
956 Min => format_pl_smallstr!("{name}_min"),
957 Max => format_pl_smallstr!("{name}_max"),
958 NanMin => format_pl_smallstr!("{name}_nan_min"),
959 NanMax => format_pl_smallstr!("{name}_nan_max"),
960 Median => format_pl_smallstr!("{name}_median"),
961 Mean => format_pl_smallstr!("{name}_mean"),
962 First => format_pl_smallstr!("{name}_first"),
963 FirstNonNull => format_pl_smallstr!("{name}_first_non_null"),
964 Last => format_pl_smallstr!("{name}_last"),
965 LastNonNull => format_pl_smallstr!("{name}_last_non_null"),
966 Item { .. } => format_pl_smallstr!("{name}_item"),
967 Sum => format_pl_smallstr!("{name}_sum"),
968 Groups => PlSmallStr::from_static("groups"),
969 NUnique => format_pl_smallstr!("{name}_n_unique"),
970 Count { .. } => format_pl_smallstr!("{name}_count"),
971 Implode => format_pl_smallstr!("{name}_agg_list"),
972 Quantile(quantile, _interpol) => format_pl_smallstr!("{name}_quantile_{quantile:.2}"),
973 Std(_) => format_pl_smallstr!("{name}_agg_std"),
974 Var(_) => format_pl_smallstr!("{name}_agg_var"),
975 ArgMin => format_pl_smallstr!("{name}_arg_min"),
976 ArgMax => format_pl_smallstr!("{name}_arg_max"),
977 }
978}
979
980#[cfg(test)]
981mod test {
982 use num_traits::FloatConst;
983
984 use crate::prelude::*;
985
986 #[test]
987 #[cfg(feature = "dtype-date")]
988 #[cfg_attr(miri, ignore)]
989 fn test_group_by() -> PolarsResult<()> {
990 let s0 = Column::new(
991 PlSmallStr::from_static("date"),
992 &[
993 "2020-08-21",
994 "2020-08-21",
995 "2020-08-22",
996 "2020-08-23",
997 "2020-08-22",
998 ],
999 );
1000 let s1 = Column::new(PlSmallStr::from_static("temp"), [20, 10, 7, 9, 1]);
1001 let s2 = Column::new(PlSmallStr::from_static("rain"), [0.2, 0.1, 0.3, 0.1, 0.01]);
1002 let df = DataFrame::new_infer_height(vec![s0, s1, s2]).unwrap();
1003
1004 let out = df.group_by_stable(["date"])?.select(["temp"]).count()?;
1005 assert_eq!(
1006 out.column("temp_count")?,
1007 &Column::new(PlSmallStr::from_static("temp_count"), [2 as IdxSize, 2, 1])
1008 );
1009
1010 #[allow(deprecated)]
1012 let out = df
1014 .group_by_stable(["date"])?
1015 .select(["temp", "rain"])
1016 .mean()?;
1017 assert_eq!(
1018 out.column("temp_mean")?,
1019 &Column::new(PlSmallStr::from_static("temp_mean"), [15.0f64, 4.0, 9.0])
1020 );
1021
1022 #[allow(deprecated)]
1024 let out = df
1026 .group_by_stable(["date", "temp"])?
1027 .select(["rain"])
1028 .mean()?;
1029 assert!(out.column("rain_mean").is_ok());
1030
1031 #[allow(deprecated)]
1033 let out = df.group_by_stable(["date"])?.select(["temp"]).sum()?;
1034 assert_eq!(
1035 out.column("temp_sum")?,
1036 &Column::new(PlSmallStr::from_static("temp_sum"), [30, 8, 9])
1037 );
1038
1039 #[allow(deprecated)]
1041 let gb = df.group_by(["date"]).unwrap().n_unique().unwrap();
1043 assert_eq!(gb.width(), 3);
1045 Ok(())
1046 }
1047
1048 #[test]
1049 #[cfg_attr(miri, ignore)]
1050 fn test_static_group_by_by_12_columns() {
1051 let s0 = Column::new("G1".into(), ["A", "A", "B", "B", "C"].as_ref());
1053 let s1 = Column::new("N".into(), [1, 2, 2, 4, 2].as_ref());
1054 let s2 = Column::new("G2".into(), ["k", "l", "m", "m", "l"].as_ref());
1055 let s3 = Column::new("G3".into(), ["a", "b", "c", "c", "d"].as_ref());
1056 let s4 = Column::new("G4".into(), ["1", "2", "3", "3", "4"].as_ref());
1057 let s5 = Column::new("G5".into(), ["X", "Y", "Z", "Z", "W"].as_ref());
1058 let s6 = Column::new("G6".into(), [false, true, true, true, false].as_ref());
1059 let s7 = Column::new("G7".into(), ["r", "x", "q", "q", "o"].as_ref());
1060 let s8 = Column::new("G8".into(), ["R", "X", "Q", "Q", "O"].as_ref());
1061 let s9 = Column::new("G9".into(), [1, 2, 3, 3, 4].as_ref());
1062 let s10 = Column::new("G10".into(), [".", "!", "?", "?", "/"].as_ref());
1063 let s11 = Column::new("G11".into(), ["(", ")", "@", "@", "$"].as_ref());
1064 let s12 = Column::new("G12".into(), ["-", "_", ";", ";", ","].as_ref());
1065
1066 let df = DataFrame::new_infer_height(vec![
1067 s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12,
1068 ])
1069 .unwrap();
1070
1071 #[allow(deprecated)]
1073 let adf = df
1074 .group_by([
1075 "G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9", "G10", "G11", "G12",
1076 ])
1077 .unwrap()
1078 .select(["N"])
1079 .sum()
1080 .unwrap();
1081
1082 assert_eq!(
1083 Vec::from(&adf.column("N_sum").unwrap().i32().unwrap().sort(false)),
1084 &[Some(1), Some(2), Some(2), Some(6)]
1085 );
1086 }
1087
1088 #[test]
1089 #[cfg_attr(miri, ignore)]
1090 fn test_dynamic_group_by_by_13_columns() {
1091 let series_content = ["A", "A", "B", "B", "C"];
1093
1094 let series_names = [
1096 "G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9", "G10", "G11", "G12", "G13",
1097 ];
1098
1099 let mut columns = Vec::with_capacity(14);
1101
1102 for series_name in series_names {
1104 let group_columns = Column::new(series_name.into(), series_content.as_ref());
1105 columns.push(group_columns);
1106 }
1107
1108 let agg_series = Column::new("N".into(), [1, 2, 3, 3, 4].as_ref());
1110 columns.push(agg_series);
1111
1112 let df = DataFrame::new_infer_height(columns).unwrap();
1114
1115 #[allow(deprecated)]
1117 let adf = df
1119 .group_by(series_names)
1120 .unwrap()
1121 .select(["N"])
1122 .sum()
1123 .unwrap();
1124
1125 for series_name in &series_names {
1128 assert_eq!(
1129 Vec::from(&adf.column(series_name).unwrap().str().unwrap().sort(false)),
1130 &[Some("A"), Some("B"), Some("C")]
1131 );
1132 }
1133
1134 assert_eq!(
1136 Vec::from(&adf.column("N_sum").unwrap().i32().unwrap().sort(false)),
1137 &[Some(3), Some(4), Some(6)]
1138 );
1139 }
1140
1141 #[test]
1142 #[cfg_attr(miri, ignore)]
1143 fn test_group_by_floats() {
1144 let df = df! {"flt" => [1., 1., 2., 2., 3.],
1145 "val" => [1, 1, 1, 1, 1]
1146 }
1147 .unwrap();
1148 #[allow(deprecated)]
1150 let res = df.group_by(["flt"]).unwrap().sum().unwrap();
1151 let res = res.sort(["flt"], SortMultipleOptions::default()).unwrap();
1152 assert_eq!(
1153 Vec::from(res.column("val_sum").unwrap().i32().unwrap()),
1154 &[Some(2), Some(2), Some(1)]
1155 );
1156 }
1157
1158 #[test]
1159 #[cfg_attr(miri, ignore)]
1160 #[cfg(feature = "dtype-categorical")]
1161 fn test_group_by_categorical() {
1162 let mut df = df! {"foo" => ["a", "a", "b", "b", "c"],
1163 "ham" => ["a", "a", "b", "b", "c"],
1164 "bar" => [1, 1, 1, 1, 1]
1165 }
1166 .unwrap();
1167
1168 df.apply("foo", |s| {
1169 s.cast(&DataType::from_categories(Categories::global()))
1170 .unwrap()
1171 })
1172 .unwrap();
1173
1174 #[allow(deprecated)]
1176 let res = df
1178 .group_by_stable(["foo", "ham"])
1179 .unwrap()
1180 .select(["bar"])
1181 .sum()
1182 .unwrap();
1183
1184 assert_eq!(
1185 Vec::from(
1186 res.column("bar_sum")
1187 .unwrap()
1188 .as_materialized_series()
1189 .i32()
1190 .unwrap()
1191 ),
1192 &[Some(2), Some(2), Some(1)]
1193 );
1194 }
1195
1196 #[test]
1197 #[cfg_attr(miri, ignore)]
1198 fn test_group_by_null_handling() -> PolarsResult<()> {
1199 let df = df!(
1200 "a" => ["a", "a", "a", "b", "b"],
1201 "b" => [Some(1), Some(2), None, None, Some(1)]
1202 )?;
1203 #[allow(deprecated)]
1205 let out = df.group_by_stable(["a"])?.mean()?;
1206
1207 assert_eq!(
1208 Vec::from(out.column("b_mean")?.as_materialized_series().f64()?),
1209 &[Some(1.5), Some(1.0)]
1210 );
1211 Ok(())
1212 }
1213
1214 #[test]
1215 #[cfg_attr(miri, ignore)]
1216 fn test_group_by_var() -> PolarsResult<()> {
1217 let df = df![
1219 "g" => ["foo", "foo", "bar"],
1220 "flt" => [1.0, 2.0, 3.0],
1221 "int" => [1, 2, 3]
1222 ]?;
1223
1224 #[allow(deprecated)]
1226 let out = df.group_by_stable(["g"])?.select(["int"]).var(1)?;
1227
1228 assert_eq!(out.column("int_agg_var")?.f64()?.get(0), Some(0.5));
1229 #[allow(deprecated)]
1231 let out = df.group_by_stable(["g"])?.select(["int"]).std(1)?;
1232 let val = out.column("int_agg_std")?.f64()?.get(0).unwrap();
1233 let expected = f64::FRAC_1_SQRT_2();
1234 assert!((val - expected).abs() < 0.000001);
1235 Ok(())
1236 }
1237
1238 #[test]
1239 #[cfg_attr(miri, ignore)]
1240 #[cfg(feature = "dtype-categorical")]
1241 fn test_group_by_null_group() -> PolarsResult<()> {
1242 let mut df = df![
1244 "g" => [Some("foo"), Some("foo"), Some("bar"), None, None],
1245 "flt" => [1.0, 2.0, 3.0, 1.0, 1.0],
1246 "int" => [1, 2, 3, 1, 1]
1247 ]?;
1248
1249 df.try_apply("g", |s| {
1250 s.cast(&DataType::from_categories(Categories::global()))
1251 })?;
1252
1253 #[allow(deprecated)]
1255 let _ = df.group_by(["g"])?.sum()?;
1256 Ok(())
1257 }
1258}