diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 9d1b3eaebdf8b..968db9de97093 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -293,6 +293,7 @@ Groupby/resample/rolling Reshaping ^^^^^^^^^ +- Bug in :func:`merge` raising error when performing an inner join with partial index and ``right_index`` when no overlap between indices (:issue:`33814`) - Bug in :meth:`DataFrame.unstack` with missing levels led to incorrect index names (:issue:`37510`) - Bug in :func:`concat` incorrectly casting to ``object`` dtype in some cases when one or more of the operands is empty (:issue:`38843`) - diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 1354e72cadc5a..ac5fc7cddf82a 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -864,9 +864,9 @@ def _maybe_add_join_keys(self, result, left_indexer, right_indexer): mask_left = left_indexer == -1 mask_right = right_indexer == -1 if mask_left.all(): - key_col = rvals + key_col = Index(rvals) elif right_indexer is not None and mask_right.all(): - key_col = lvals + key_col = Index(lvals) else: key_col = Index(lvals).where(~mask_left, rvals) diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index d430856776269..da3ac81c4aa17 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -2375,3 +2375,15 @@ def test_merge_right_left_index(): } ) tm.assert_frame_equal(result, expected) + + +def test_merge_result_empty_index_and_on(): + # GH#33814 + df1 = DataFrame({"a": [1], "b": [2]}).set_index(["a", "b"]) + df2 = DataFrame({"b": [1]}).set_index(["b"]) + expected = DataFrame({"a": [], "b": []}, dtype=np.int64).set_index(["a", "b"]) + result = merge(df1, df2, left_on=["b"], right_index=True) + tm.assert_frame_equal(result, expected) + + result = merge(df2, df1, left_index=True, right_on=["b"]) + tm.assert_frame_equal(result, expected)