Skip to content

issue #27642 - timedelta merge asof with tolerance #27650

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

Merged
merged 25 commits into from
Aug 22, 2019
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
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
4 changes: 2 additions & 2 deletions doc/source/whatsnew/v0.25.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Datetimelike

Timedelta
^^^^^^^^^

-
-
-
Expand Down Expand Up @@ -129,7 +129,7 @@ Reshaping
^^^^^^^^^

- A ``KeyError`` is now raised if ``.unstack()`` is called on a :class:`Series` or :class:`DataFrame` with a flat :class:`Index` passing a name which is not the correct one (:issue:`18303`)
-
- Bug in ``.merge_asof(tolerance=tolerance)`` could not merge :class:`Timedelta` objects (:issue:`27642`)
-

Sparse
Expand Down
7 changes: 6 additions & 1 deletion pandas/core/reshape/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
is_number,
is_numeric_dtype,
is_object_dtype,
is_timedelta64_dtype,
needs_i8_conversion,
)
from pandas.core.dtypes.missing import isnull, na_value_for_dtype
Expand Down Expand Up @@ -1635,7 +1636,11 @@ def _get_merge_keys(self):
)
)

if is_datetime64_dtype(lt) or is_datetime64tz_dtype(lt):
if (
is_datetime64_dtype(lt)
or is_datetime64tz_dtype(lt)
or is_timedelta64_dtype(lt)
):
if not isinstance(self.tolerance, Timedelta):
Copy link
Member

Choose a reason for hiding this comment

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

This should probably be if not isinstance(self.tolerance, datetime.timedelta) so users can pass datetime.timedelta objects. If you could add a test case for that situation that'd be great.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

see commit "mroeschke: this test is for you 🚀"

Copy link
Contributor Author

Choose a reason for hiding this comment

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

the test fails

Copy link
Contributor Author

@ianzur ianzur Jul 30, 2019

Choose a reason for hiding this comment

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

I think we'll need a different PR for this test I think, it fails at this conversion check.

# initial type conversion as needed
if needs_i8_conversion(left_values):
left_values = left_values.view("i8")
right_values = right_values.view("i8")
if tolerance is not None:
tolerance = tolerance.value

With tolerance = datetime.timedelta -> ERROR: has no attribute "value"

Copy link
Contributor Author

@ianzur ianzur Jul 30, 2019

Choose a reason for hiding this comment

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

datetime.timedelta objects do not have nanoseconds like pd.Timedelta

Another check and conversion is necessary to convert datetime.timedelta correctly to nanoseconds similarly to pd.Timedelta.value

Copy link
Member

Choose a reason for hiding this comment

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

Okay thanks for investigating. Yes, I'd be great to address in another issues/PR.

raise MergeError(msg)
if self.tolerance < Timedelta(0):
Expand Down
45 changes: 45 additions & 0 deletions pandas/tests/reshape/merge/test_merge_asof.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import numpy as np
import datetime
import pytest
import pytz

Expand Down Expand Up @@ -599,6 +600,19 @@ def test_tolerance(self):
expected = self.tolerance
assert_frame_equal(result, expected)

def test_datetime_timedelta_tolerance(self):
# this will fail

trades = self.trades
quotes = self.quotes

result = merge_asof(
trades, quotes, on="time", by="ticker", tolerance=datetime.timedelta(days=1)
)
expected = self.tolerance

assert_frame_equal(result, expected)

def test_tolerance_forward(self):
# GH14887

Expand Down Expand Up @@ -1246,3 +1260,34 @@ def test_by_mixed_tz_aware(self):
)
expected["value_y"] = np.array([np.nan], dtype=object)
assert_frame_equal(result, expected)

def test_timedelta_tolerance_nearest(self):
# GH 27642

left = pd.DataFrame(
{
"time": pd.to_timedelta([0, 5, 10, 15, 20, 25], "ms"),
"left": [0, 1, 2, 3, 4, 5],
}
)

right = pd.DataFrame(
{
"time": pd.to_timedelta([0, 3, 9, 12, 15, 18], "ms"),
"right": [0, 1, 2, 3, 4, 5],
}
)

expected = pd.DataFrame(
{
"time": pd.to_timedelta([0, 5, 10, 15, 20, 25], "ms"),
"left": [0, 1, 2, 3, 4, 5],
"right": [0, np.nan, 2, 4, np.nan, np.nan],
}
)

result = pd.merge_asof(
left, right, on="time", tolerance=pd.Timedelta("1ms"), direction="nearest"
)

assert_frame_equal(result, expected)