Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-plan/src/dsl/struct_.rs
8430 views
1
use super::*;
2
use crate::dsl::functions::nth;
3
use crate::plans::conversion::is_regex_projection;
4
5
/// Specialized expressions for Struct dtypes.
6
pub struct StructNameSpace(pub(crate) Expr);
7
8
impl StructNameSpace {
9
pub fn field_by_index(self, index: i64) -> Expr {
10
self.0
11
.map_unary(FunctionExpr::StructExpr(StructFunction::SelectFields(nth(
12
index,
13
))))
14
}
15
16
/// Retrieve one or multiple of the fields of this [`StructChunked`] as a new Series.
17
/// This expression also expands the `"*"` wildcard column.
18
pub fn field_by_names<I, S>(self, names: I) -> Expr
19
where
20
I: IntoIterator<Item = S>,
21
S: Into<PlSmallStr>,
22
{
23
self.field_by_names_impl(names.into_iter().map(|x| x.into()).collect())
24
}
25
26
fn field_by_names_impl(self, names: Arc<[PlSmallStr]>) -> Expr {
27
let mut selector = Selector::Empty;
28
let _s = &mut selector;
29
let names = names
30
.iter()
31
.filter(|n| {
32
match n.as_str() {
33
_ if is_regex_projection(n.as_str()) => *_s |= Selector::Matches((*n).clone()),
34
"*" => *_s |= Selector::Wildcard,
35
_ => return true,
36
}
37
38
false
39
})
40
.cloned()
41
.collect();
42
selector |= Selector::ByName {
43
names,
44
strict: true,
45
};
46
47
self.0
48
.map_unary(FunctionExpr::StructExpr(StructFunction::SelectFields(
49
selector,
50
)))
51
}
52
53
/// Retrieve one of the fields of this [`StructChunked`] as a new Series.
54
/// This expression also supports wildcard "*" and regex expansion.
55
pub fn field_by_name(self, name: &str) -> Expr {
56
if name == "*" || is_regex_projection(name) {
57
return self.field_by_names([name]);
58
}
59
self.0
60
.map_unary(FunctionExpr::StructExpr(StructFunction::FieldByName(
61
name.into(),
62
)))
63
}
64
65
/// Rename the fields of the [`StructChunked`].
66
pub fn rename_fields<I, S>(self, names: I) -> Expr
67
where
68
I: IntoIterator<Item = S>,
69
S: Into<PlSmallStr>,
70
{
71
self._rename_fields_impl(names.into_iter().map(|x| x.into()).collect())
72
}
73
74
pub fn _rename_fields_impl(self, names: Arc<[PlSmallStr]>) -> Expr {
75
self.0
76
.map_unary(FunctionExpr::StructExpr(StructFunction::RenameFields(
77
names,
78
)))
79
}
80
81
#[cfg(feature = "json")]
82
pub fn json_encode(self) -> Expr {
83
self.0
84
.map_unary(FunctionExpr::StructExpr(StructFunction::JsonEncode))
85
}
86
87
pub fn with_fields(self, fields: Vec<Expr>) -> Expr {
88
Expr::StructEval {
89
expr: Arc::new(self.0),
90
evaluation: fields,
91
}
92
}
93
}
94
95