Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-plan/src/dsl/functions/selectors.rs
6940 views
1
use super::*;
2
3
/// Create a Column Expression based on a column name.
4
///
5
/// # Arguments
6
///
7
/// * `name` - A string slice that holds the name of the column. If a column with this name does not exist when the
8
/// LazyFrame is collected, an error is returned.
9
///
10
/// # Examples
11
///
12
/// ```ignore
13
/// // select a column name
14
/// col("foo")
15
/// ```
16
///
17
/// ```ignore
18
/// // select all columns by using a wildcard
19
/// col("*")
20
/// ```
21
///
22
/// ```ignore
23
/// // select specific columns by writing a regular expression that starts with `^` and ends with `$`
24
/// // only if regex features is activated
25
/// col("^foo.*$")
26
/// ```
27
pub fn col<S>(name: S) -> Expr
28
where
29
S: Into<PlSmallStr>,
30
{
31
let name = name.into();
32
match name.as_str() {
33
"*" => all().as_expr(),
34
n if is_regex_projection(n) => Expr::Selector(Selector::Matches(name)),
35
_ => Expr::Column(name),
36
}
37
}
38
39
/// Selects no columns.
40
pub fn empty() -> Selector {
41
Selector::Empty
42
}
43
44
/// Selects all columns.
45
pub fn all() -> Selector {
46
Selector::Wildcard
47
}
48
49
/// Select multiple columns by name.
50
pub fn cols<I, S>(names: I) -> Selector
51
where
52
I: IntoIterator<Item = S>,
53
S: Into<PlSmallStr>,
54
{
55
by_name(names, true)
56
}
57
58
/// Select multiple columns by dtype.
59
pub fn dtype_col(dtype: &DataType) -> DataTypeSelector {
60
DataTypeSelector::AnyOf([dtype.clone()].into())
61
}
62
63
/// Select multiple columns by dtype.
64
pub fn dtype_cols<DT: AsRef<[DataType]>>(dtype: DT) -> DataTypeSelector {
65
let dtypes = dtype.as_ref();
66
DataTypeSelector::AnyOf(dtypes.into())
67
}
68
69
/// Select multiple columns by dtype.
70
pub fn by_name<S: Into<PlSmallStr>, I: IntoIterator<Item = S>>(names: I, strict: bool) -> Selector {
71
let mut selector = None;
72
let _s = &mut selector;
73
let names = names
74
.into_iter()
75
.map(Into::into)
76
.filter_map(|name| match name.as_str() {
77
"*" => {
78
*_s = Some(std::mem::take(_s).map_or(all(), |s| s | all()));
79
None
80
},
81
n if is_regex_projection(n) => {
82
let m = Selector::Matches(name);
83
*_s = Some(std::mem::take(_s).map_or_else(|| m.clone(), |s| s | m.clone()));
84
None
85
},
86
_ => Some(name),
87
})
88
.collect::<Arc<[_]>>();
89
90
let no_names = names.is_empty();
91
let names = Selector::ByName { names, strict };
92
if let Some(selector) = selector {
93
if no_names { selector } else { selector | names }
94
} else {
95
names
96
}
97
}
98
99
/// Select multiple columns by index.
100
pub fn index_cols<N: AsRef<[i64]>>(indices: N) -> Selector {
101
let indices = indices.as_ref().into();
102
Selector::ByIndex {
103
indices,
104
strict: true,
105
}
106
}
107
108