Skip to content

Commit 28c4358

Browse files
committed
BUG: Keep float dtype in merge on int and float column
1 parent 8d04daf commit 28c4358

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

pandas/core/reshape/merge.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -906,13 +906,20 @@ def _maybe_coerce_merge_keys(self):
906906
continue
907907

908908
# if we are numeric, then allow differing
909-
# kinds to proceed, eg. int64 and int8
909+
# kinds to proceed, eg. int64 and int8, int and float
910910
# further if we are object, but we infer to
911911
# the same, then proceed
912912
if is_numeric_dtype(lk) and is_numeric_dtype(rk):
913913
if lk.dtype.kind == rk.dtype.kind:
914914
continue
915915

916+
# check whether ints and floats
917+
if is_integer_dtype(rk) and is_float_dtype(lk):
918+
continue
919+
920+
if is_float_dtype(rk) and is_integer_dtype(lk):
921+
continue
922+
916923
# let's infer and see if we are ok
917924
if lib.infer_dtype(lk) == lib.infer_dtype(rk):
918925
continue

pandas/tests/reshape/test_merge.py

+24-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,11 @@
1313
from pandas.core.reshape.merge import merge, MergeError
1414
from pandas.util.testing import assert_frame_equal, assert_series_equal
1515
from pandas.core.dtypes.dtypes import CategoricalDtype
16-
from pandas.core.dtypes.common import is_categorical_dtype, is_object_dtype
16+
from pandas.core.dtypes.common import (
17+
is_categorical_dtype,
18+
is_object_dtype,
19+
is_float_dtype,
20+
)
1721
from pandas import DataFrame, Index, MultiIndex, Series, Categorical
1822
import pandas.util.testing as tm
1923
from pandas.api.types import CategoricalDtype as CDT
@@ -1408,6 +1412,25 @@ def test_join_multi_dtypes(self, d1, d2):
14081412
expected.sort_values(['k1', 'k2'], kind='mergesort', inplace=True)
14091413
tm.assert_frame_equal(result, expected)
14101414

1415+
@pytest.mark.parametrize('int_vals, float_vals', [
1416+
([1, 2, 3], [1.0, 2.0, 3.0]),
1417+
([1, 2, 3], [1.0, 3.0]),
1418+
([1, 2], [1.0, 2.0, 3.0]),
1419+
([1, 2, 3], [1.1, 2.5, 3.0]),
1420+
])
1421+
def test_merge_on_ints_floats(self, int_vals, float_vals):
1422+
# GH 16572
1423+
# Check that float column is not cast to object if
1424+
# merging on float and int
1425+
A = DataFrame({'X': int_vals})
1426+
B = DataFrame({'Y': float_vals})
1427+
1428+
res = A.merge(B, left_on='X', right_on='Y')
1429+
assert is_float_dtype(res['Y'].dtype)
1430+
1431+
res = B.merge(A, left_on='Y', right_on='X')
1432+
assert is_float_dtype(res['Y'].dtype)
1433+
14111434

14121435
@pytest.fixture
14131436
def left():

0 commit comments

Comments
 (0)