Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-expr/src/expressions/field.rs
8424 views
1
use polars_core::error::PolarsResult;
2
use polars_core::frame::DataFrame;
3
use polars_core::prelude::{Column, Field, GroupPositions};
4
use polars_plan::dsl::Expr;
5
6
use super::*;
7
use crate::prelude::AggregationContext;
8
use crate::state::ExecutionState;
9
10
#[derive(Clone)]
11
pub struct FieldExpr {
12
name: PlSmallStr,
13
expr: Expr,
14
output_field: Field,
15
}
16
17
impl FieldExpr {
18
pub fn new(name: PlSmallStr, expr: Expr, output_field: Field) -> Self {
19
Self {
20
name,
21
expr,
22
output_field,
23
}
24
}
25
}
26
27
impl PhysicalExpr for FieldExpr {
28
fn as_expression(&self) -> Option<&Expr> {
29
Some(&self.expr)
30
}
31
32
// In-memory engine only.
33
fn evaluate(&self, _df: &DataFrame, state: &ExecutionState) -> PolarsResult<Column> {
34
let ca = state
35
.with_fields
36
.as_ref()
37
.ok_or_else(|| polars_err!(invalid_field_use))?;
38
39
ca.field_by_name(self.name.as_str()).map(Column::from)
40
}
41
42
// In-memory engine only.
43
fn evaluate_on_groups<'a>(
44
&self,
45
_df: &DataFrame,
46
_groups: &'a GroupPositions,
47
state: &ExecutionState,
48
) -> PolarsResult<AggregationContext<'a>> {
49
let ac = state
50
.with_fields_ac
51
.as_ref()
52
.ok_or_else(|| polars_err!(invalid_field_use))?;
53
54
let col = ac.flat_naive().clone();
55
let ca = col.struct_()?;
56
let out = ca.field_by_name(self.name.as_str()).map(Column::from)?;
57
58
Ok(AggregationContext {
59
state: match ac.agg_state() {
60
AggState::AggregatedList(_) => AggState::AggregatedList(out),
61
AggState::NotAggregated(_) => AggState::NotAggregated(out),
62
AggState::AggregatedScalar(_) => AggState::AggregatedScalar(out),
63
AggState::LiteralScalar(_) => AggState::LiteralScalar(out),
64
},
65
groups: ac.groups.clone(),
66
update_groups: ac.update_groups,
67
original_len: ac.original_len,
68
})
69
}
70
71
fn to_field(&self, _input_schema: &Schema) -> PolarsResult<Field> {
72
Ok(self.output_field.clone())
73
}
74
75
fn is_scalar(&self) -> bool {
76
false
77
}
78
}
79
80