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/mode.rs
6939 views
1
use polars_core::POOL;
2
use polars_core::prelude::*;
3
4
fn mode_indices(groups: GroupsType) -> Vec<IdxSize> {
5
match groups {
6
GroupsType::Idx(groups) => {
7
let Some(max_len) = groups.iter().map(|g| g.1.len()).max() else {
8
return Vec::new();
9
};
10
groups
11
.into_iter()
12
.filter(|g| g.1.len() == max_len)
13
.map(|g| g.0)
14
.collect()
15
},
16
GroupsType::Slice { groups, .. } => {
17
let Some(max_len) = groups.iter().map(|g| g[1]).max() else {
18
return Vec::new();
19
};
20
groups
21
.into_iter()
22
.filter(|g| g[1] == max_len)
23
.map(|g| g[0])
24
.collect()
25
},
26
}
27
}
28
29
pub fn mode(s: &Series) -> PolarsResult<Series> {
30
let parallel = !POOL.current_thread_has_pending_tasks().unwrap_or(false);
31
let groups = s.group_tuples(parallel, false).unwrap();
32
let idx = mode_indices(groups);
33
let idx = IdxCa::from_vec("".into(), idx);
34
// SAFETY:
35
// group indices are in bounds
36
Ok(unsafe { s.take_unchecked(&idx) })
37
}
38
39