Path: blob/main/crates/polars-expr/src/expressions/rolling.rs
6940 views
use polars_time::{PolarsTemporalGroupby, RollingGroupOptions};12use super::*;34pub(crate) struct RollingExpr {5/// the root column that the Function will be applied on.6/// This will be used to create a smaller DataFrame to prevent taking unneeded columns by index7/// TODO! support keys?8/// The challenge is that the group_by will reorder the results and the9/// keys, and time index would need to be updated, or the result should be joined back10/// For now, don't support it.11///12/// A function Expr. i.e. Mean, Median, Max, etc.13pub(crate) function: Expr,14pub(crate) phys_function: Arc<dyn PhysicalExpr>,15pub(crate) options: RollingGroupOptions,16pub(crate) expr: Expr,17}1819impl PhysicalExpr for RollingExpr {20fn evaluate(&self, df: &DataFrame, state: &ExecutionState) -> PolarsResult<Column> {21let groups_key = format!("{:?}", &self.options);2223let groups = {24// Groups must be set by expression runner.25state.window_cache.get_groups(&groups_key)26};2728// There can be multiple rolling expressions in a single expr.29// E.g. `min().rolling() + max().rolling()`30// So if we hit that we will compute them here.31let groups = match groups {32Some(groups) => groups,33None => {34let (_time_key, groups) = df.rolling(None, &self.options)?;35state.window_cache.insert_groups(groups_key, groups.clone());36groups37},38};3940let out = self41.phys_function42.evaluate_on_groups(df, &groups, state)?43.finalize();44polars_ensure!(out.len() == groups.len(), agg_len = out.len(), groups.len());45Ok(out.into_column())46}4748fn evaluate_on_groups<'a>(49&self,50_df: &DataFrame,51_groups: &'a GroupPositions,52_state: &ExecutionState,53) -> PolarsResult<AggregationContext<'a>> {54polars_bail!(InvalidOperation: "rolling expression not allowed in aggregation");55}5657fn to_field(&self, input_schema: &Schema) -> PolarsResult<Field> {58self.function.to_field(input_schema)59}6061fn as_expression(&self) -> Option<&Expr> {62Some(&self.expr)63}6465fn is_scalar(&self) -> bool {66false67}68}697071