Skip to content

BUG: merge should upcast to highest resolution #56310

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

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.4.rst
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Bug fixes
- Fixed bug in :func:`to_numeric` converting to extension dtype for ``string[pyarrow_numpy]`` dtype (:issue:`56179`)
- Fixed bug in :meth:`DataFrame.__setitem__` casting :class:`Index` with object-dtype to PyArrow backed strings when ``infer_string`` option is set (:issue:`55638`)
- Fixed bug in :meth:`DataFrame.to_hdf` raising when columns have ``StringDtype`` (:issue:`55088`)
- Fixed bug in :meth:`DataFrame.merge` not being able to join on ``datetime64`` columns or differing resolutions (:issue:`55212`)
- Fixed bug in :meth:`Index.insert` casting object-dtype to PyArrow backed strings when ``infer_string`` option is set (:issue:`55638`)
- Fixed bug in :meth:`Series.mode` not keeping object dtype when ``infer_string`` is set (:issue:`56183`)
- Fixed bug in :meth:`Series.str.translate` losing object dtype when string option is set (:issue:`56152`)
Expand Down
10 changes: 1 addition & 9 deletions pandas/core/reshape/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -1073,16 +1073,8 @@ def _maybe_add_join_keys(
key_col = Index(lvals)
result_dtype = lvals.dtype
else:
key_col = Index(lvals).where(~mask_left, rvals)
result_dtype = find_common_type([lvals.dtype, rvals.dtype])
if (
lvals.dtype.kind == "M"
and rvals.dtype.kind == "M"
and result_dtype.kind == "O"
):
# TODO(non-nano) Workaround for common_type not dealing
# with different resolutions
result_dtype = key_col.dtype
key_col = Index(lvals).astype(result_dtype).where(~mask_left, rvals)
Copy link
Member

Choose a reason for hiding this comment

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

pass copy=False?


if result._is_label_reference(name):
result[name] = result._constructor_sliced(
Expand Down
25 changes: 19 additions & 6 deletions pandas/tests/reshape/merge/test_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -2818,7 +2818,8 @@ def test_merge_arrow_and_numpy_dtypes(dtype):

@pytest.mark.parametrize("how", ["inner", "left", "outer", "right"])
@pytest.mark.parametrize("tz", [None, "America/Chicago"])
def test_merge_datetime_different_resolution(tz, how):
@pytest.mark.parametrize("unit", ["us", "ms", "s"])
def test_merge_datetime_different_resolution(tz, how, unit):
# https://github.com/pandas-dev/pandas/issues/53200
vals = [
pd.Timestamp(2023, 5, 12, tz=tz),
Expand All @@ -2828,19 +2829,31 @@ def test_merge_datetime_different_resolution(tz, how):
df1 = DataFrame({"t": vals[:2], "a": [1.0, 2.0]})
df1["t"] = df1["t"].dt.as_unit("ns")
df2 = DataFrame({"t": vals[1:], "b": [1.0, 2.0]})
df2["t"] = df2["t"].dt.as_unit("s")
df2["t"] = df2["t"].dt.as_unit(unit)

expected = DataFrame({"t": vals, "a": [1.0, 2.0, np.nan], "b": [np.nan, 1.0, 2.0]})
expected["t"] = expected["t"].dt.as_unit("ns")
if how == "inner":
expected = expected.iloc[[1]].reset_index(drop=True)
expected1 = expected.iloc[[1]].reset_index(drop=True)
expected2 = expected1
elif how == "left":
expected = expected.iloc[[0, 1]]
expected1 = expected.iloc[[0, 1]]
expected2 = expected.iloc[[1, 2]].reset_index(drop=True)
elif how == "right":
expected = expected.iloc[[1, 2]].reset_index(drop=True)
expected1 = expected.iloc[[1, 2]].reset_index(drop=True)
expected2 = expected.iloc[[0, 1]]
else:
expected1 = expected
expected2 = expected

result = df1.merge(df2, on="t", how=how)
tm.assert_frame_equal(result, expected)
tm.assert_frame_equal(result, expected1)

# Check lower resolution to higher resolution also works
# GH55212
expected2 = expected2[["t", "b", "a"]]
result1 = df2.merge(df1, on="t", how=how)
tm.assert_frame_equal(result1, expected2)


def test_merge_multiindex_single_level():
Expand Down