Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-ops/src/chunked_array/array/to_struct.rs
6939 views
1
use polars_core::POOL;
2
use polars_utils::format_pl_smallstr;
3
use polars_utils::pl_str::PlSmallStr;
4
use rayon::prelude::*;
5
6
use super::*;
7
8
pub type ArrToStructNameGenerator = Arc<dyn Fn(usize) -> PolarsResult<PlSmallStr> + Send + Sync>;
9
10
pub fn arr_default_struct_name_gen(idx: usize) -> PlSmallStr {
11
format_pl_smallstr!("field_{idx}")
12
}
13
14
pub trait ToStruct: AsArray {
15
fn to_struct(
16
&self,
17
name_generator: Option<ArrToStructNameGenerator>,
18
) -> PolarsResult<StructChunked> {
19
let ca = self.as_array();
20
let n_fields = ca.width();
21
22
let name_generator = name_generator
23
.as_deref()
24
.unwrap_or(&|i| Ok(arr_default_struct_name_gen(i)));
25
26
let fields = POOL.install(|| {
27
(0..n_fields)
28
.into_par_iter()
29
.map(|i| {
30
ca.array_get(
31
&Int64Chunked::from_slice(PlSmallStr::EMPTY, &[i as i64]),
32
true,
33
)
34
.and_then(|mut s| {
35
s.rename(name_generator(i)?);
36
Ok(s)
37
})
38
})
39
.collect::<PolarsResult<Vec<_>>>()
40
})?;
41
42
StructChunked::from_series(ca.name().clone(), ca.len(), fields.iter())
43
}
44
}
45
46
impl ToStruct for ArrayChunked {}
47
48