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/concat.rs
8432 views
1
use super::*;
2
3
#[cfg(all(feature = "concat_str", feature = "strings"))]
4
/// Horizontally concat string columns in linear time
5
pub fn concat_str<E: AsRef<[Expr]>>(s: E, separator: &str, ignore_nulls: bool) -> Expr {
6
let input = s.as_ref().to_vec();
7
let separator = separator.into();
8
9
Expr::Function {
10
input,
11
function: StringFunction::ConcatHorizontal {
12
delimiter: separator,
13
ignore_nulls,
14
}
15
.into(),
16
}
17
}
18
19
#[cfg(all(feature = "concat_str", feature = "strings"))]
20
/// Format the results of an array of expressions using a format string
21
pub fn format_str<E: AsRef<[Expr]>>(format: &str, args: E) -> PolarsResult<Expr> {
22
let input = args.as_ref().to_vec();
23
24
let mut s = String::with_capacity(format.len());
25
let mut insertions = Vec::with_capacity(input.len());
26
let mut offset = 0;
27
while let Some(j) = format[offset..].find("{}") {
28
s.push_str(&format[offset..][..j]);
29
insertions.push(s.len());
30
offset += j + 2;
31
}
32
s.push_str(&format[offset..]);
33
34
polars_ensure!(
35
insertions.len() == input.len(),
36
ShapeMismatch: "number of placeholders should equal the number of arguments"
37
);
38
39
Ok(Expr::Function {
40
input,
41
function: StringFunction::Format {
42
format: s.into(),
43
insertions: insertions.into(),
44
}
45
.into(),
46
})
47
}
48
49
/// Concat lists entries.
50
pub fn concat_list<E: AsRef<[IE]>, IE: Into<Expr> + Clone>(s: E) -> PolarsResult<Expr> {
51
let s: Vec<_> = s.as_ref().iter().map(|e| e.clone().into()).collect();
52
53
polars_ensure!(!s.is_empty(), ComputeError: "`concat_list` needs one or more expressions");
54
55
Ok(Expr::Function {
56
input: s,
57
function: FunctionExpr::ListExpr(ListFunction::Concat),
58
})
59
}
60
61
/// Horizontally concatenate columns into a single array-type column.
62
pub fn concat_arr(input: Vec<Expr>) -> PolarsResult<Expr> {
63
feature_gated!("dtype-array", {
64
polars_ensure!(!input.is_empty(), ComputeError: "`concat_arr` needs one or more expressions");
65
66
Ok(Expr::Function {
67
input,
68
function: FunctionExpr::ArrayExpr(ArrayFunction::Concat),
69
})
70
})
71
}
72
73
pub fn concat_expr<E: AsRef<[IE]>, IE: Into<Expr> + Clone>(
74
s: E,
75
rechunk: bool,
76
) -> PolarsResult<Expr> {
77
let s: Vec<_> = s.as_ref().iter().map(|e| e.clone().into()).collect();
78
polars_ensure!(!s.is_empty(), ComputeError: "`concat_expr` needs one or more expressions");
79
Ok(Expr::n_ary(FunctionExpr::ConcatExpr(rechunk), s))
80
}
81
82