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