Skip to content

Commit

Permalink
fix truncate in case of window offset
Browse files Browse the repository at this point in the history
  • Loading branch information
ritchie46 committed Dec 20, 2021
1 parent 3f99163 commit d3b0f0d
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
3 changes: 2 additions & 1 deletion polars/polars-core/src/frame/groupby/dynamic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,8 @@ impl DataFrame {
}

if options.truncate {
dt = dt.apply(|v| w.truncate(v));
let w = Window::new(options.every, options.period, options.offset);
dt = dt.apply(|v| w.truncate_no_offset(v));
}

if let (true, Some(lower), Some(higher)) =
Expand Down
5 changes: 5 additions & 0 deletions polars/polars-time/src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ impl Window {
self.every.truncate_nanoseconds(t) + self.offset
}

#[inline]
pub fn truncate_no_offset(&self, t: TimeNanoseconds) -> TimeNanoseconds {
self.every.truncate_nanoseconds(t)
}

/// returns the bounds for the earliest window bounds
/// that contains the given time t. For underlapping windows that
/// do not contain time t, the window directly after time t will be returned.
Expand Down
30 changes: 30 additions & 0 deletions py-polars/tests/test_datelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,33 @@ def test_date_comp() -> None:
a = pl.Series("a", [one, two])
assert (a == one).to_list() == [True, False]
assert (a == two).to_list() == [False, True]


def test_truncate_negative_offset() -> None:
df = pl.DataFrame(
{
"event_date": [
datetime(2021, 4, 11),
datetime(2021, 4, 29),
datetime(2021, 5, 29),
],
"adm1_code": [1, 2, 1],
}
)
out = df.groupby_dynamic(
time_column="event_date",
every="1mo",
period="2mo",
offset="-1mo",
include_boundaries=True,
).agg(
[
pl.col("adm1_code"),
]
)

assert out["event_date"].to_list() == [
datetime(2021, 4, 1),
datetime(2021, 4, 1),
datetime(2021, 5, 1),
]

0 comments on commit d3b0f0d

Please sign in to comment.