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, python): fix 'filter' in groupby context when expression is… #7041

Merged
merged 1 commit into from
Feb 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
170 changes: 84 additions & 86 deletions polars/polars-lazy/src/physical_plan/expressions/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,96 +48,94 @@ impl PhysicalExpr for FilterExpr {
let (ac_s, ac_predicate) = POOL.install(|| rayon::join(ac_s_f, ac_predicate_f));
let (mut ac_s, mut ac_predicate) = (ac_s?, ac_predicate?);

match ac_predicate.is_aggregated() {
true => {
let preds = ac_predicate.iter_groups();
let s = ac_s.aggregated();
let ca = s.list()?;
let mut out = ca
.amortized_iter()
.zip(preds)
.map(|(opt_s, opt_pred)| match (opt_s, opt_pred) {
(Some(s), Some(pred)) => s.as_ref().filter(pred.as_ref().bool()?).map(Some),
_ => Ok(None),
})
.collect::<PolarsResult<ListChunked>>()?;
out.rename(s.name());
ac_s.with_series(out.into_series(), true, Some(&self.expr))?;
ac_s.update_groups = WithSeriesLen;
Ok(ac_s)
if ac_predicate.is_aggregated() || ac_s.is_aggregated() {
let preds = ac_predicate.iter_groups();
let s = ac_s.aggregated();
let ca = s.list()?;
let mut out = ca
.amortized_iter()
.zip(preds)
.map(|(opt_s, opt_pred)| match (opt_s, opt_pred) {
(Some(s), Some(pred)) => s.as_ref().filter(pred.as_ref().bool()?).map(Some),
_ => Ok(None),
})
.collect::<PolarsResult<ListChunked>>()?;
out.rename(s.name());
ac_s.with_series(out.into_series(), true, Some(&self.expr))?;
ac_s.update_groups = WithSeriesLen;
Ok(ac_s)
} else {
let groups = ac_s.groups();
let predicate_s = ac_predicate.flat_naive();
let predicate = predicate_s.bool()?;

// all values true don't do anything
if predicate.all() {
return Ok(ac_s);
}
false => {
let groups = ac_s.groups();
let predicate_s = ac_predicate.flat_naive();
let predicate = predicate_s.bool()?.rechunk();

// all values true don't do anything
if predicate.all() {
return Ok(ac_s);
// all values false
// create empty groups
let groups = if !predicate.any() {
let groups = groups.iter().map(|gi| [gi.first(), 0]).collect::<Vec<_>>();
GroupsProxy::Slice {
groups,
rolling: false,
}
// all values false
// create empty groups
let groups = if !predicate.any() {
let groups = groups.iter().map(|gi| [gi.first(), 0]).collect::<Vec<_>>();
GroupsProxy::Slice {
groups,
rolling: false,
}
}
// filter the indexes that are true
else {
let predicate = predicate.downcast_iter().next().unwrap();
POOL.install(|| {
match groups.as_ref() {
GroupsProxy::Idx(groups) => {
let groups = groups
.par_iter()
.map(|(first, idx)| unsafe {
let idx: Vec<IdxSize> = idx
.iter()
// Safety:
// just checked bounds in short circuited lhs
.filter_map(|i| {
match predicate.value(*i as usize)
&& predicate.is_valid_unchecked(*i as usize)
{
true => Some(*i),
_ => None,
}
})
.collect();

(*idx.first().unwrap_or(&first), idx)
})
.collect();

GroupsProxy::Idx(groups)
}
GroupsProxy::Slice { groups, .. } => {
let groups = groups
.par_iter()
.map(|&[first, len]| unsafe {
let idx: Vec<IdxSize> = (first..first + len)
// Safety:
// just checked bounds in short circuited lhs
.filter(|&i| {
predicate.value(i as usize)
&& predicate.is_valid_unchecked(i as usize)
})
.collect();

(*idx.first().unwrap_or(&first), idx)
})
.collect();
GroupsProxy::Idx(groups)
}
}
// filter the indexes that are true
else {
let predicate = predicate.rechunk();
let predicate = predicate.downcast_iter().next().unwrap();
POOL.install(|| {
match groups.as_ref() {
GroupsProxy::Idx(groups) => {
let groups = groups
.par_iter()
.map(|(first, idx)| unsafe {
let idx: Vec<IdxSize> = idx
.iter()
// Safety:
// just checked bounds in short circuited lhs
.filter_map(|i| {
match predicate.value(*i as usize)
&& predicate.is_valid_unchecked(*i as usize)
{
true => Some(*i),
_ => None,
}
})
.collect();

(*idx.first().unwrap_or(&first), idx)
})
.collect();

GroupsProxy::Idx(groups)
}
})
};
GroupsProxy::Slice { groups, .. } => {
let groups = groups
.par_iter()
.map(|&[first, len]| unsafe {
let idx: Vec<IdxSize> = (first..first + len)
// Safety:
// just checked bounds in short circuited lhs
.filter(|&i| {
predicate.value(i as usize)
&& predicate.is_valid_unchecked(i as usize)
})
.collect();

(*idx.first().unwrap_or(&first), idx)
})
.collect();
GroupsProxy::Idx(groups)
}
}
})
};

ac_s.with_groups(groups).set_original_len(false);
Ok(ac_s)
}
ac_s.with_groups(groups).set_original_len(false);
Ok(ac_s)
}
}

Expand Down
18 changes: 0 additions & 18 deletions polars/polars-lazy/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,21 +150,3 @@ pub(crate) fn get_df() -> DataFrame {
.unwrap();
df
}

#[test]
fn test_foo() {
let df: DataFrame = df![
"a" => [1u64]
]
.unwrap();

let s = df.column("a").unwrap().clone();

let df = df
.lazy()
.select([lit(s).floor_div(lit(1i64))])
.collect()
.unwrap();

dbg!(df);
}
26 changes: 26 additions & 0 deletions polars/tests/it/lazy/groupby.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,29 @@ fn test_logical_mean_partitioned_groupby_block() -> PolarsResult<()> {

Ok(())
}

#[test]
fn test_filter_aggregated_expression() -> PolarsResult<()> {
let df: DataFrame = df![
"day" => [2, 2, 2, 2, 2, 2, 1, 1],
"y" => [Some(4), Some(5), Some(8), Some(7), Some(9), None, None, None],
"x" => [1, 2, 3, 4, 5, 6, 1, 2],
]?;

let f = col("y").is_not_null().and(col("x").is_not_null());

let df = df
.lazy()
.groupby([col("day")])
.agg([(col("x") - col("x").first()).filter(f)])
.sort("day", Default::default())
.collect()
.unwrap();
let x = df.column("x")?;

assert_eq!(
x.get(1).unwrap(),
AnyValue::List(Series::new("", [0, 1, 2, 3, 4]))
);
Ok(())
}