Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-expr/src/expressions/alias.rs
6940 views
1
use polars_core::prelude::*;
2
3
use super::*;
4
use crate::expressions::{AggregationContext, PartitionedAggregation, PhysicalExpr};
5
6
pub struct AliasExpr {
7
pub(crate) physical_expr: Arc<dyn PhysicalExpr>,
8
pub(crate) name: PlSmallStr,
9
expr: Expr,
10
}
11
12
impl AliasExpr {
13
pub fn new(physical_expr: Arc<dyn PhysicalExpr>, name: PlSmallStr, expr: Expr) -> Self {
14
Self {
15
physical_expr,
16
name,
17
expr,
18
}
19
}
20
21
fn finish(&self, input: Column) -> Column {
22
input.with_name(self.name.clone())
23
}
24
}
25
26
impl PhysicalExpr for AliasExpr {
27
fn as_expression(&self) -> Option<&Expr> {
28
Some(&self.expr)
29
}
30
31
fn evaluate(&self, df: &DataFrame, state: &ExecutionState) -> PolarsResult<Column> {
32
let series = self.physical_expr.evaluate(df, state)?;
33
Ok(self.finish(series))
34
}
35
36
#[allow(clippy::ptr_arg)]
37
fn evaluate_on_groups<'a>(
38
&self,
39
df: &DataFrame,
40
groups: &'a GroupPositions,
41
state: &ExecutionState,
42
) -> PolarsResult<AggregationContext<'a>> {
43
let mut ac = self.physical_expr.evaluate_on_groups(df, groups, state)?;
44
let c = ac.take();
45
let c = self.finish(c);
46
47
if ac.is_literal() {
48
ac.with_literal(c);
49
} else {
50
ac.with_values(c, ac.is_aggregated(), Some(&self.expr))?;
51
}
52
Ok(ac)
53
}
54
55
fn to_field(&self, input_schema: &Schema) -> PolarsResult<Field> {
56
Ok(Field::new(
57
self.name.clone(),
58
self.physical_expr.to_field(input_schema)?.dtype().clone(),
59
))
60
}
61
62
fn is_literal(&self) -> bool {
63
self.physical_expr.is_literal()
64
}
65
66
fn is_scalar(&self) -> bool {
67
self.physical_expr.is_scalar()
68
}
69
70
fn as_partitioned_aggregator(&self) -> Option<&dyn PartitionedAggregation> {
71
Some(self)
72
}
73
}
74
75
impl PartitionedAggregation for AliasExpr {
76
fn evaluate_partitioned(
77
&self,
78
df: &DataFrame,
79
groups: &GroupPositions,
80
state: &ExecutionState,
81
) -> PolarsResult<Column> {
82
let agg = self.physical_expr.as_partitioned_aggregator().unwrap();
83
let s = agg.evaluate_partitioned(df, groups, state)?;
84
Ok(s.with_name(self.name.clone()))
85
}
86
87
fn finalize(
88
&self,
89
partitioned: Column,
90
groups: &GroupPositions,
91
state: &ExecutionState,
92
) -> PolarsResult<Column> {
93
let agg = self.physical_expr.as_partitioned_aggregator().unwrap();
94
let s = agg.finalize(partitioned, groups, state)?;
95
Ok(s.with_name(self.name.clone()))
96
}
97
}
98
99