Skip to main content

DataFrameGroupBy

Struct DataFrameGroupBy 

Source
pub struct DataFrameGroupBy<'a> { /* private fields */ }
Expand description

Deferred GroupBy object for DataFrame.

Created by DataFrame::groupby(). Call aggregation methods to produce results.

Implementations§

Source§

impl DataFrameGroupBy<'_>

Source

pub fn keys(&self) -> Vec<IndexLabel>

Group labels in group iteration order.

Source

pub fn indices(&self) -> HashMap<IndexLabel, Vec<usize>>

Mapping from group labels to source row positions.

Source

pub fn groups(&self) -> HashMap<IndexLabel, Vec<usize>>

Alias for indices, matching pandas’ groups property shape.

Source

pub fn grouper(&self) -> Vec<String>

Names of the columns used as groupers.

Source

pub fn level(&self) -> Vec<String>

Names of the grouping levels.

Source

pub fn ngroups(&self) -> usize

Number of groups.

Source

pub fn ndim(&self) -> usize

Grouped object dimensionality.

Source

pub fn dtypes(&self) -> Result<Series, FrameError>

DTypes for grouped value columns.

Source

pub fn plot(&self) -> Result<PlotSpec, FrameError>

Return a backend-neutral pandas-style grouped plotting request.

Source

pub fn bar(&self) -> Result<PlotSpec, FrameError>

Return a backend-neutral pandas-style grouped bar plot request.

Source

pub fn area(&self) -> Result<PlotSpec, FrameError>

Return a backend-neutral pandas-style grouped area plot request.

Source

pub fn scatter(&self) -> Result<PlotSpec, FrameError>

Return a backend-neutral pandas-style grouped scatter plot request.

Source

pub fn pie(&self) -> Result<PlotSpec, FrameError>

Return a backend-neutral pandas-style grouped pie plot request.

Source

pub fn hist(&self) -> Result<HistogramSpec, FrameError>

Return a backend-neutral pandas-style grouped histogram request.

Source

pub fn boxplot(&self) -> Result<BoxPlotSpec, FrameError>

Return a backend-neutral pandas-style grouped boxplot request.

Source

pub fn any(&self) -> Result<DataFrame, FrameError>

GroupBy any (returns True if any value is truthy per group).

Source

pub fn all(&self) -> Result<DataFrame, FrameError>

GroupBy all (returns True if all values are truthy per group).

Source

pub fn quantile(&self, q: f64) -> Result<DataFrame, FrameError>

GroupBy quantile.

Source

pub fn sum(&self) -> Result<DataFrame, FrameError>

GroupBy sum.

Source

pub fn mean(&self) -> Result<DataFrame, FrameError>

GroupBy mean.

Source

pub fn count(&self) -> Result<DataFrame, FrameError>

GroupBy count.

Source

pub fn min(&self) -> Result<DataFrame, FrameError>

GroupBy min.

Source

pub fn max(&self) -> Result<DataFrame, FrameError>

GroupBy max.

Source

pub fn std(&self) -> Result<DataFrame, FrameError>

GroupBy std.

Source

pub fn var(&self) -> Result<DataFrame, FrameError>

GroupBy var.

Source

pub fn median(&self) -> Result<DataFrame, FrameError>

GroupBy median.

Source

pub fn idxmin(&self) -> Result<DataFrame, FrameError>

GroupBy idxmin. Returns the index label of the minimum value for each group.

Source

pub fn idxmax(&self) -> Result<DataFrame, FrameError>

GroupBy idxmax. Returns the index label of the maximum value for each group.

Source

pub fn first(&self) -> Result<DataFrame, FrameError>

GroupBy first.

Source

pub fn last(&self) -> Result<DataFrame, FrameError>

GroupBy last.

Source

pub fn nunique(&self) -> Result<DataFrame, FrameError>

GroupBy nunique (count of unique non-null values per group).

Source

pub fn prod(&self) -> Result<DataFrame, FrameError>

GroupBy prod (product of non-null values per group).

Source

pub fn agg( &self, func_map: &HashMap<String, String>, ) -> Result<DataFrame, FrameError>

Aggregate with per-column function mapping.

Matches df.groupby(col).agg({'B': 'sum', 'C': 'mean'}) semantics.

func_map: mapping of column_name → aggregation function name. Only the specified columns are included in the output.

Source

pub fn aggregate( &self, func_map: &HashMap<String, String>, ) -> Result<DataFrame, FrameError>

pandas spelling alias for Self::agg.

Source

pub fn agg_list(&self, funcs: &[&str]) -> Result<DataFrame, FrameError>

Aggregate with multiple functions applied to all value columns.

Matches df.groupby(col).agg(['sum', 'mean']) semantics.

Returns a DataFrame where each original value column is expanded into N columns (one per function), named {col}_{func}.

Source

pub fn agg_dict_list( &self, func_map: &HashMap<String, Vec<String>>, ) -> Result<DataFrame, FrameError>

Aggregate with a per-column list of functions.

Matches df.groupby(col).agg({'a': ['sum', 'mean'], 'b': ['min']}) semantics. For each entry in func_map, every function is applied to the named input column, producing one output column per (input_col, func) pair named {col}_{func}. Output column order follows the original DataFrame’s column order; funcs within a column follow the slice order supplied. Columns not in func_map are excluded, group-by key columns are rejected, and an empty func list is rejected.

Source

pub fn agg_named( &self, specs: &[(&str, &str, &str)], ) -> Result<DataFrame, FrameError>

Named aggregation: each tuple is (output_name, input_column, function).

Matches df.groupby('g').agg(out=('col', 'func')) in pandas. The output DataFrame has columns named by output_name, computed by applying function to input_column within each group.

Example:

ⓘ
let result = df.groupby(&["region"]).unwrap().agg_named(&[
    ("total_sales", "revenue", "sum"),
    ("avg_price", "price", "mean"),
    ("num_orders", "order_id", "count"),
]).unwrap();
Source

pub fn agg_multi( &self, func_map: &HashMap<String, Vec<String>>, ) -> Result<DataFrame, FrameError>

Aggregate with multiple functions per column.

Matches df.groupby(col).agg({'A': ['sum', 'mean'], 'B': ['count']}). Output columns are named {col}_{func}.

Source

pub fn apply<F>(&self, func: F) -> Result<DataFrame, FrameError>

Apply a custom function to each group DataFrame.

Matches pandas 2.x df.groupby(col).apply(func, include_groups=False) for DataFrame-returning functions. Results are concatenated vertically; multi-row group results receive group-key row MultiIndex metadata.

Source

pub fn apply_with_include_groups<F>( &self, include_groups: bool, func: F, ) -> Result<DataFrame, FrameError>

Apply a DataFrame-returning function with explicit include_groups.

Source

pub fn apply_scalar<F>(&self, name: &str, func: F) -> Result<Series, FrameError>

Apply a scalar-returning function to each group.

Rust’s static return types expose pandas’ scalar-returning GroupBy.apply shape as an explicit API: one Series value per group, indexed by the group keys.

Source

pub fn apply_scalar_with_include_groups<F>( &self, name: &str, include_groups: bool, func: F, ) -> Result<Series, FrameError>

Apply a scalar-returning function with explicit include_groups.

Source

pub fn apply_series<F>(&self, func: F) -> Result<DataFrame, FrameError>

Apply a Series-returning function to each group.

Returned Series indexes become output columns. The column union is first-seen ordered and groups missing a Series label receive NaN, which matches pandas’ sparse DataFrame shape for uneven Series returns.

Source

pub fn apply_series_with_include_groups<F>( &self, include_groups: bool, func: F, ) -> Result<DataFrame, FrameError>

Apply a Series-returning function with explicit include_groups.

Source

pub fn apply_series_stacked<F>( &self, name: &str, func: F, ) -> Result<DataFrame, FrameError>

Apply a Series-returning function and stack each returned Series row.

This is the Rust API for pandas’ GroupBy.apply path where returned Series objects do not share identical labels. The result is represented as a one-column DataFrame because Series does not yet carry row MultiIndex metadata; group keys and returned Series labels are retained on the DataFrame row MultiIndex.

Source

pub fn apply_series_stacked_with_include_groups<F>( &self, name: &str, include_groups: bool, func: F, ) -> Result<DataFrame, FrameError>

Apply a stacked Series-returning function with explicit include_groups.

Source

pub fn transform(&self, func_name: &str) -> Result<DataFrame, FrameError>

Source

pub fn transform_list(&self, funcs: &[&str]) -> Result<DataFrame, FrameError>

Transform each group with multiple named aggregation functions.

Matches df.groupby(col).transform(['sum', 'mean']) for the supported function set. One output column is produced per {input_column}_{func} pair, and each aggregated value is broadcast back to the original row positions of its group.

Source

pub fn transform_fn<F>(&self, func: F) -> Result<DataFrame, FrameError>
where F: Fn(&Series) -> Result<Series, FrameError>,

Transform each group using a user-supplied closure.

Matches df.groupby(col).transform(lambda s: ...) — the closure receives a per-group Series (one call per value column × per group) and must return a Series of the same length. Values are scattered back to their original row positions, so the output DataFrame has the same shape and index as the input. Group-by key columns are excluded from the transform (matching pandas). The closure returning a Series whose length differs from its input is rejected.

Source

pub fn size(&self) -> Result<Series, FrameError>

GroupBy size (number of rows per group).

Source

pub fn filter<F>(&self, func: F) -> Result<DataFrame, FrameError>
where F: Fn(&DataFrame) -> Result<bool, FrameError>,

Filter groups using a function that returns bool for each group.

Analogous to df.groupby(col).filter(func). The function receives a sub-DataFrame for each group and should return true to keep the group or false to drop it. Returns a DataFrame containing only the rows belonging to kept groups, preserving original index and column order.

Source

pub fn cumsum(&self) -> Result<DataFrame, FrameError>

GroupBy cumulative sum.

Matches df.groupby(col).cumsum().

Source

pub fn cumprod(&self) -> Result<DataFrame, FrameError>

GroupBy cumulative product.

Matches df.groupby(col).cumprod().

Source

pub fn cummax(&self) -> Result<DataFrame, FrameError>

GroupBy cumulative max.

Matches df.groupby(col).cummax().

Source

pub fn cummin(&self) -> Result<DataFrame, FrameError>

GroupBy cumulative min.

Matches df.groupby(col).cummin().

Source

pub fn rank( &self, method: &str, ascending: bool, na_option: &str, ) -> Result<DataFrame, FrameError>

GroupBy rank within each group.

Matches df.groupby(col).rank(). method: “average” (default), “min”, “max”, “first”, “dense” ascending: rank direction (default true = smallest gets rank 1) na_option: “keep” (NaN stays NaN), “top” (NaN gets lowest ranks), “bottom” (NaN gets highest ranks)

Source

pub fn rank_with_pct( &self, method: &str, ascending: bool, na_option: &str, pct: bool, ) -> Result<DataFrame, FrameError>

GroupBy rank within each group and optionally scale the ranks to percentiles.

Source

pub fn shift(&self, periods: i64) -> Result<DataFrame, FrameError>

GroupBy shift within each group.

Matches df.groupby(col).shift(periods).

Source

pub fn diff(&self, periods: usize) -> Result<DataFrame, FrameError>

GroupBy diff within each group.

Matches df.groupby(col).diff(periods).

Source

pub fn nth(&self, n: i64) -> Result<DataFrame, FrameError>

GroupBy nth: select the nth row from each group.

Matches df.groupby(col).nth(n). Returns a DataFrame with one row per group. Negative n counts from the end.

Source

pub fn head(&self, n: i64) -> Result<DataFrame, FrameError>

GroupBy head: select first n rows per group.

Matches df.groupby(col).head(n), including pandas’ negative n: head(-k) keeps all but the last k rows of each group. Verified vs live pandas 2.2.3.

Source

pub fn tail(&self, n: i64) -> Result<DataFrame, FrameError>

GroupBy tail: select last n rows per group.

Matches df.groupby(col).tail(n), including pandas’ negative n: tail(-k) drops the first k rows of each group. Verified vs live pandas 2.2.3.

Source

pub fn take(&self, indices: &[i64]) -> Result<DataFrame, FrameError>

Return positional rows from each group.

Matches pd.DataFrameGroupBy.take(indices), resolving negative positions relative to each group’s length.

Source

pub fn sample( &self, n: Option<usize>, frac: Option<f64>, replace: bool, seed: Option<u64>, ) -> Result<DataFrame, FrameError>

Randomly sample rows from each group.

Matches pd.DataFrameGroupBy.sample(n=..., frac=..., replace=...).

Source

pub fn pct_change(&self, periods: i64) -> Result<DataFrame, FrameError>

GroupBy pct_change within each group.

Matches df.groupby(col).pct_change().

Source

pub fn value_counts(&self) -> Result<DataFrame, FrameError>

GroupBy value_counts: count of each unique value per group.

Matches df.groupby(col)[value_col].value_counts(). Returns a DataFrame with group key + value as index and counts as values.

Source

pub fn describe(&self) -> Result<DataFrame, FrameError>

GroupBy describe: summary statistics per group.

Matches df.groupby(col).describe(). Returns count, mean, std, min, 25%/50%/75% quantiles, and max for each group’s numeric columns.

Source

pub fn get_group(&self, name: &str) -> Result<DataFrame, FrameError>

Retrieve a single group as a DataFrame.

Matches groupby.get_group(name). The name should match the debug representation of the group key value (e.g. "a" for Utf8 or "Int64(1)" for numeric keys).

Source

pub fn cumcount(&self) -> Result<Series, FrameError>

Assign within-group cumulative count (0-based).

Matches groupby.cumcount(). Returns a Series of Int64 with a monotonically increasing counter within each group.

Source

pub fn cumcount_with_ascending( &self, ascending: bool, ) -> Result<Series, FrameError>

Assign within-group cumulative count (0-based) with explicit direction.

Matches groupby.cumcount(ascending=...).

Source

pub fn ngroup(&self) -> Result<Series, FrameError>

Assign group number to each row.

Matches groupby.ngroup(). Returns a Series of Int64 where each row gets the ordinal number of its group.

Source

pub fn ngroup_with_ascending( &self, ascending: bool, ) -> Result<Series, FrameError>

Assign group number to each row with explicit numbering direction.

Matches groupby.ngroup(ascending=...). Rows skipped by dropna=True keep NaN, while included groups are numbered in iteration order or in reverse when ascending is false.

Source

pub fn pipe<F>(&self, func: F) -> Result<DataFrame, FrameError>
where F: FnOnce(&Self) -> Result<DataFrame, FrameError>,

Pipe the GroupBy through a function.

Matches groupby.pipe(func).

Source

pub fn corr(&self) -> Result<DataFrame, FrameError>

Pairwise Pearson correlation matrix per group.

Matches pd.DataFrameGroupBy.corr() by stacking each group’s DataFrame correlation matrix under group-key row metadata.

Source

pub fn cov(&self) -> Result<DataFrame, FrameError>

Pairwise covariance matrix per group.

Matches pd.DataFrameGroupBy.cov() by stacking each group’s DataFrame covariance matrix under group-key row metadata.

Source

pub fn corrwith(&self, other: &DataFrame) -> Result<DataFrame, FrameError>

Column-wise correlation against another DataFrame per group.

Matches the DataFrameGroupBy.corrwith(other) result shape: one row per group and one column per shared numeric column.

Source

pub fn sem(&self) -> Result<DataFrame, FrameError>

Standard error of the mean per group.

Matches groupby.sem(). Computed as std / sqrt(count).

Source

pub fn skew(&self) -> Result<DataFrame, FrameError>

Skewness per group (Fisher’s definition, bias=False).

Matches groupby.skew().

Source

pub fn kurtosis(&self) -> Result<DataFrame, FrameError>

Kurtosis per group (Fisher’s excess, bias=False).

Matches groupby.kurtosis().

Source

pub fn kurt(&self) -> Result<DataFrame, FrameError>

Alias for kurtosis() — pandas exposes both df.groupby(by).kurt() and .kurtosis(). Parity requires both spellings.

Source

pub fn ohlc(&self) -> Result<DataFrame, FrameError>

Open-High-Low-Close per group.

Matches the current FrankenPandas groupby.ohlc() data contract. The returned DataFrame keeps its flat storage column names while carrying the pandas-style column MultiIndex in sidecar metadata.

Source

pub fn ohlc_column_multiindex(&self) -> Result<MultiIndex, FrameError>

pandas-style column MultiIndex for groupby.ohlc().

The first level is the source value column and the second level is one of open, high, low, or close.

Source

pub fn ohlc_with_column_multiindex( &self, ) -> Result<(DataFrame, MultiIndex), FrameError>

Return the current flat OHLC frame plus pandas-style MultiIndex columns.

Source

pub fn ffill(&self, limit: Option<usize>) -> Result<DataFrame, FrameError>

Forward-fill missing values within each group.

Matches pd.GroupBy.ffill(). Within each group, fills NaN values with the preceding non-NaN value.

Source

pub fn bfill(&self, limit: Option<usize>) -> Result<DataFrame, FrameError>

Backward-fill missing values within each group.

Matches pd.GroupBy.bfill(). Within each group, fills NaN values with the next non-NaN value.

Source

pub fn fillna(&self, value: &Scalar) -> Result<DataFrame, FrameError>

Fill missing values within each group using a scalar.

Matches pd.GroupBy.fillna(value).

Source

pub fn expanding(&self, min_periods: Option<usize>) -> GroupByExpanding<'_>

Grouped expanding window operations.

Matches pd.DataFrameGroupBy.expanding(min_periods=...).

Source

pub fn ewm(&self, span: Option<f64>, alpha: Option<f64>) -> GroupByEwm<'_>

Grouped exponentially weighted moving window operations.

Matches pd.DataFrameGroupBy.ewm(span=..., alpha=...).

Source

pub fn rolling(&self, window: usize) -> GroupByRolling<'_>

Grouped rolling window operations.

Matches pd.DataFrameGroupBy.rolling(window). Returns a GroupByRolling struct that applies rolling operations per group.

Source

pub fn resample(&self, freq: &str) -> GroupByResample<'_>

Grouped resampling.

Matches pd.DataFrameGroupBy.resample(freq). Returns a GroupByResample struct that applies resampling per group.

Auto Trait Implementations§

§

impl<'a> Freeze for DataFrameGroupBy<'a>

§

impl<'a> RefUnwindSafe for DataFrameGroupBy<'a>

§

impl<'a> Send for DataFrameGroupBy<'a>

§

impl<'a> Sync for DataFrameGroupBy<'a>

§

impl<'a> Unpin for DataFrameGroupBy<'a>

§

impl<'a> UnsafeUnpin for DataFrameGroupBy<'a>

§

impl<'a> UnwindSafe for DataFrameGroupBy<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.