Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(rust): Prevent panic on sample_n with replacement from empty df #10731

Merged
merged 2 commits into from
Aug 26, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions crates/polars-core/src/chunked_array/random.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ use crate::random::get_global_random_u64;
use crate::utils::{CustomIterTools, NoNull};

fn create_rand_index_with_replacement(n: usize, len: usize, seed: Option<u64>) -> IdxCa {
if len == 0 {
return NoNull::<IdxCa>::from_iter(std::iter::empty()).into_inner();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you use IdxCa::new_empty

}
let mut rng = SmallRng::seed_from_u64(seed.unwrap_or_else(get_global_random_u64));
let dist = Uniform::new(0, len as IdxSize);
(0..n as IdxSize)
Expand Down Expand Up @@ -257,6 +260,22 @@ impl BooleanChunked {
mod test {
use super::*;

#[test]
fn test_sample_empty_df() {
trueb2 marked this conversation as resolved.
Show resolved Hide resolved
let df = df![
"foo" => Vec::<i32>::new()
]
.unwrap();

// If with replacement, then expect empty df
assert_eq!(df.sample_n(3, true, false, None).unwrap().height(), 0);
assert_eq!(df.sample_frac(0.4, true, false, None).unwrap().height(), 0);

// If without replacement, then expect shape mismatch on sample_n not sample_frac
assert!(df.sample_n(3, false, false, None).is_err());
assert_eq!(df.sample_frac(0.4, false, false, None).unwrap().height(), 0);
}

#[test]
fn test_sample() {
let df = df![
Expand Down