Skip to content

Commit 2d5ccaa

Browse files
committed
Add cross functionality for join
1 parent 949185e commit 2d5ccaa

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

pandas/core/frame.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8069,6 +8069,15 @@ def _join_compat(
80698069
other = DataFrame({other.name: other})
80708070

80718071
if isinstance(other, DataFrame):
8072+
if how == "cross":
8073+
return merge(
8074+
self,
8075+
other,
8076+
how=how,
8077+
on=on,
8078+
suffixes=(lsuffix, rsuffix),
8079+
sort=sort,
8080+
)
80728081
return merge(
80738082
self,
80748083
other,

pandas/tests/reshape/merge/test_join.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import pandas as pd
55
from pandas import DataFrame, Index, MultiIndex, Series, concat, merge
66
import pandas._testing as tm
7+
from pandas.errors import MergeError
78
from pandas.tests.reshape.merge.test_merge import NGROUPS, N, get_test_data
89

910
a_ = np.array
@@ -803,3 +804,24 @@ def test_join_inner_multiindex_deterministic_order():
803804
index=MultiIndex.from_tuples([(2, 1, 4, 3)], names=("b", "a", "d", "c")),
804805
)
805806
tm.assert_frame_equal(result, expected)
807+
808+
809+
@pytest.mark.parametrize(
810+
("input_col", "output_cols"), [("b", ["a", "b"]), ("a", ["a_x", "a_y"])]
811+
)
812+
def test_join_cross(input_col, output_cols):
813+
# GH#5401
814+
left = DataFrame({"a": [1, 3]})
815+
right = DataFrame({input_col: [3, 4]})
816+
result = left.join(right, how="cross", lsuffix="_x", rsuffix="_y")
817+
expected = DataFrame({output_cols[0]: [1, 1, 3, 3], output_cols[1]: [3, 4, 3, 4]})
818+
tm.assert_frame_equal(result, expected)
819+
820+
821+
def test_join_cross_error_reporting():
822+
# GH#5401
823+
left = DataFrame({"a": [1, 3]})
824+
right = DataFrame({"a": [3, 4]})
825+
msg = "Can not pass any merge columns when using cross as merge method"
826+
with pytest.raises(MergeError, match=msg):
827+
left.join(right, how="cross", on="a")

0 commit comments

Comments
 (0)