Skip to content

ENH: Add merge type validation on pandas.merge #59435

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
Show file tree
Hide file tree
Changes from 6 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/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ Other enhancements
^^^^^^^^^^^^^^^^^^
- :class:`pandas.api.typing.FrozenList` is available for typing the outputs of :attr:`MultiIndex.names`, :attr:`MultiIndex.codes` and :attr:`MultiIndex.levels` (:issue:`58237`)
- :class:`pandas.api.typing.SASReader` is available for typing the output of :func:`read_sas` (:issue:`55689`)
- :func:`pandas.merge` now validates the ``how`` parameter input (merge type) (:issue:`59435`)
- :func:`DataFrame.to_excel` now raises an ``UserWarning`` when the character count in a cell exceeds Excel's limitation of 32767 characters (:issue:`56954`)
- :func:`read_stata` now returns ``datetime64`` resolutions better matching those natively stored in the stata format (:issue:`55642`)
- :meth:`DataFrame.agg` called with ``axis=1`` and a ``func`` which relabels the result index now raises a ``NotImplementedError`` (:issue:`58807`).
Expand Down
5 changes: 5 additions & 0 deletions pandas/core/reshape/merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -982,6 +982,11 @@ def __init__(
)
raise MergeError(msg)

# GH 59435: raise when "how" is not a valid Merge type
merge_type = ("left", "right", "inner", "outer", "cross", "asof")
if how not in merge_type:
raise ValueError(f"'{how}' is not a valid Merge type {merge_type}")

self.left_on, self.right_on = self._validate_left_right_on(left_on, right_on)

(
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/reshape/merge/test_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -1456,6 +1456,21 @@ def test_merge_readonly(self):

data1.merge(data2) # no error

def test_merge_how_validation(self):
# https://github.com/pandas-dev/pandas/issues/59422
data1 = DataFrame(
np.arange(20).reshape((4, 5)) + 1, columns=["a", "b", "c", "d", "e"]
)
data2 = DataFrame(
np.arange(20).reshape((5, 4)) + 1, columns=["a", "b", "x", "y"]
)
msg = (
"'full' is not a valid Merge type "
"('left', 'right', 'inner', 'outer', 'cross', 'asof')"
)
with pytest.raises(ValueError, match=re.escape(msg)):
data1.merge(data2, how="full")


def _check_merge(x, y):
for how in ["inner", "left", "outer"]:
Expand Down
Loading