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
6940 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 mut args: std::collections::VecDeque<Expr> = args.as_ref().to_vec().into();
23
24
// Parse the format string, and separate substrings between placeholders
25
let segments: Vec<&str> = format.split("{}").collect();
26
27
polars_ensure!(
28
segments.len() - 1 == args.len(),
29
ShapeMismatch: "number of placeholders should equal the number of arguments"
30
);
31
32
let mut exprs: Vec<Expr> = Vec::new();
33
34
for (i, s) in segments.iter().enumerate() {
35
if i > 0 {
36
if let Some(arg) = args.pop_front() {
37
exprs.push(arg);
38
}
39
}
40
41
if !s.is_empty() {
42
exprs.push(lit(s.to_string()))
43
}
44
}
45
46
Ok(concat_str(exprs, "", false))
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