Skip to content

Commit

Permalink
Fix mode for multiple modes (#3566)
Browse files Browse the repository at this point in the history
  • Loading branch information
GregoryBL committed Jun 8, 2022
1 parent 20ce6e8 commit 89f94b5
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions polars/polars-core/src/chunked_array/ops/unique/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,21 +142,16 @@ where
.into_iter()
.collect_trusted::<Vec<_>>();
groups.sort_unstable_by_key(|k| k.1.len());
let first = &groups[0];
let last = &groups.last().unwrap();

let max_occur = first.1.len();
let max_occur = last.1.len();

// collect until we don't take with trusted len anymore
// TODO! take directly from iter, but first remove standard trusted-length collect.
let mut was_equal = true;
let idx = groups
.iter()
.rev()
.take_while(|v| {
let current = was_equal;
was_equal = v.1.len() == max_occur;
current
})
.take_while(|v| v.1.len() == max_occur)
.map(|v| v.0)
.collect::<Vec<_>>();
// Safety:
Expand Down Expand Up @@ -457,4 +452,22 @@ mod test {
]
);
}

#[test]
#[cfg(feature = "mode")]
fn mode() {
let ca = Int32Chunked::from_slice("a", &[0, 1, 2, 3, 4, 4, 5, 6, 5, 0]);
let mut result = Vec::from(&ca.mode().unwrap());
result.sort_by(|a, b| a.unwrap().cmp(&b.unwrap()));
assert_eq!(&result, &[Some(0), Some(4), Some(5)]);

let ca2 = Int32Chunked::from_slice("b", &[1, 1]);
let mut result2 = Vec::from(&ca2.mode().unwrap());
result2.sort_by(|a, b| a.unwrap().cmp(&b.unwrap()));
assert_eq!(&result2, &[Some(1)]);

let ca3 = Int32Chunked::from_slice("c", &[]);
let result3 = Vec::from(&ca3.mode().unwrap());
assert_eq!(result3, &[]);
}
}

0 comments on commit 89f94b5

Please sign in to comment.