Skip to content

Commit 80c4961

Browse files
committed
BUG/API: .merge() and .join() on category dtype columns will now preserve the category dtype when possible
closes #10409
1 parent cd67704 commit 80c4961

File tree

8 files changed

+269
-70
lines changed

8 files changed

+269
-70
lines changed

asv_bench/benchmarks/join_merge.py

+30-6
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from pandas import ordered_merge as merge_ordered
77

88

9-
#----------------------------------------------------------------------
9+
# ----------------------------------------------------------------------
1010
# Append
1111

1212
class Append(object):
@@ -35,7 +35,7 @@ def time_append_mixed(self):
3535
self.mdf1.append(self.mdf2)
3636

3737

38-
#----------------------------------------------------------------------
38+
# ----------------------------------------------------------------------
3939
# Concat
4040

4141
class Concat(object):
@@ -120,7 +120,7 @@ def time_f_ordered_axis1(self):
120120
concat(self.frames_f, axis=1, ignore_index=True)
121121

122122

123-
#----------------------------------------------------------------------
123+
# ----------------------------------------------------------------------
124124
# Joins
125125

126126
class Join(object):
@@ -202,7 +202,7 @@ def time_join_non_unique_equal(self):
202202
(self.fracofday * self.temp[self.fracofday.index])
203203

204204

205-
#----------------------------------------------------------------------
205+
# ----------------------------------------------------------------------
206206
# Merges
207207

208208
class Merge(object):
@@ -257,7 +257,31 @@ def time_i8merge(self):
257257
merge(self.left, self.right, how='outer')
258258

259259

260-
#----------------------------------------------------------------------
260+
class MergeCategoricals(object):
261+
goal_time = 0.2
262+
263+
def setup(self):
264+
self.left_object = pd.DataFrame(
265+
{'X': np.random.choice(range(0, 10), size=(10000,)),
266+
'Y': np.random.choice(['one', 'two', 'three'], size=(10000,))})
267+
268+
self.right_object = pd.DataFrame(
269+
{'X': np.random.choice(range(0, 10), size=(10000,)),
270+
'Z': np.random.choice(['jjj', 'kkk', 'sss'], size=(10000,))})
271+
272+
self.left_cat = self.left_object.assign(
273+
Y=self.left_object['Y'].astype('category'))
274+
self.right_cat = self.right_object.assign(
275+
Z=self.right_object['Z'].astype('category'))
276+
277+
def time_merge_object(self):
278+
merge(self.left_object, self.right_object, on='X')
279+
280+
def time_merge_cat(self):
281+
merge(self.left_cat, self.right_cat, on='X')
282+
283+
284+
# ----------------------------------------------------------------------
261285
# Ordered merge
262286

263287
class MergeOrdered(object):
@@ -332,7 +356,7 @@ def time_multiby(self):
332356
merge_asof(self.df1e, self.df2e, on='time', by=['key', 'key2'])
333357

334358

335-
#----------------------------------------------------------------------
359+
# ----------------------------------------------------------------------
336360
# data alignment
337361

338362
class Align(object):

doc/source/whatsnew/v0.20.0.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,7 @@ Other API Changes
519519
- The :func:`pd.read_gbq` method now stores ``INTEGER`` columns as ``dtype=object`` if they contain ``NULL`` values. Otherwise they are stored as ``int64``. This prevents precision lost for integers greather than 2**53. Furthermore ``FLOAT`` columns with values above 10**4 are no longer casted to ``int64`` which also caused precision loss (:issue:`14064`, :issue:`14305`).
520520
- Reorganization of timeseries development tests (:issue:`14854`)
521521
- Specific support for ``copy.copy()`` and ``copy.deepcopy()`` functions on NDFrame objects (:issue:`15444`)
522+
- ``.merge()`` and ``.join()`` on ``category`` dtype columns will now preserve the category dtype when possible (:issue:`10409`)
522523

523524
.. _whatsnew_0200.deprecations:
524525

@@ -567,7 +568,7 @@ Performance Improvements
567568
- Improved performance and reduced memory when indexing with a ``MultiIndex`` (:issue:`15245`)
568569
- When reading buffer object in ``read_sas()`` method without specified format, filepath string is inferred rather than buffer object. (:issue:`14947`)
569570
- Improved performance of `rank()` for categorical data (:issue:`15498`)
570-
571+
- Improved performance of merge/join on ``category`` columns (:issue:`10409`)
571572

572573

573574
.. _whatsnew_0200.bug_fixes:

pandas/core/internals.py

+2
Original file line numberDiff line numberDiff line change
@@ -5228,6 +5228,8 @@ def get_reindexed_values(self, empty_dtype, upcasted_na):
52285228
# External code requested filling/upcasting, bool values must
52295229
# be upcasted to object to avoid being upcasted to numeric.
52305230
values = self.block.astype(np.object_).values
5231+
elif self.block.is_categorical:
5232+
values = self.block.values
52315233
else:
52325234
# No dtype upcasting is done here, it will be performed during
52335235
# concatenation itself.

pandas/tests/test_categorical.py

+3
Original file line numberDiff line numberDiff line change
@@ -4097,9 +4097,12 @@ def test_merge(self):
40974097
expected = df.copy()
40984098

40994099
# object-cat
4100+
# note that we propogate the category
4101+
# because we don't have any matching rows
41004102
cright = right.copy()
41014103
cright['d'] = cright['d'].astype('category')
41024104
result = pd.merge(left, cright, how='left', left_on='b', right_on='c')
4105+
expected['d'] = expected['d'].astype('category', categories=['null'])
41034106
tm.assert_frame_equal(result, expected)
41044107

41054108
# cat-object

pandas/tests/tools/test_merge.py

+139-32
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
from pandas.tools.concat import concat
1212
from pandas.tools.merge import merge, MergeError
1313
from pandas.util.testing import assert_frame_equal, assert_series_equal
14+
from pandas.types.dtypes import CategoricalDtype
15+
from pandas.types.common import is_categorical_dtype, is_object_dtype
1416
from pandas import DataFrame, Index, MultiIndex, Series, Categorical
1517
import pandas.util.testing as tm
1618

@@ -1024,38 +1026,6 @@ def test_left_join_index_multi_match(self):
10241026
expected.index = np.arange(len(expected))
10251027
tm.assert_frame_equal(result, expected)
10261028

1027-
def test_join_multi_dtypes(self):
1028-
1029-
# test with multi dtypes in the join index
1030-
def _test(dtype1, dtype2):
1031-
left = DataFrame({'k1': np.array([0, 1, 2] * 8, dtype=dtype1),
1032-
'k2': ['foo', 'bar'] * 12,
1033-
'v': np.array(np.arange(24), dtype=np.int64)})
1034-
1035-
index = MultiIndex.from_tuples([(2, 'bar'), (1, 'foo')])
1036-
right = DataFrame(
1037-
{'v2': np.array([5, 7], dtype=dtype2)}, index=index)
1038-
1039-
result = left.join(right, on=['k1', 'k2'])
1040-
1041-
expected = left.copy()
1042-
1043-
if dtype2.kind == 'i':
1044-
dtype2 = np.dtype('float64')
1045-
expected['v2'] = np.array(np.nan, dtype=dtype2)
1046-
expected.loc[(expected.k1 == 2) & (expected.k2 == 'bar'), 'v2'] = 5
1047-
expected.loc[(expected.k1 == 1) & (expected.k2 == 'foo'), 'v2'] = 7
1048-
1049-
tm.assert_frame_equal(result, expected)
1050-
1051-
result = left.join(right, on=['k1', 'k2'], sort=True)
1052-
expected.sort_values(['k1', 'k2'], kind='mergesort', inplace=True)
1053-
tm.assert_frame_equal(result, expected)
1054-
1055-
for d1 in [np.int64, np.int32, np.int16, np.int8, np.uint8]:
1056-
for d2 in [np.int64, np.float64, np.float32, np.float16]:
1057-
_test(np.dtype(d1), np.dtype(d2))
1058-
10591029
def test_left_merge_na_buglet(self):
10601030
left = DataFrame({'id': list('abcde'), 'v1': randn(5),
10611031
'v2': randn(5), 'dummy': list('abcde'),
@@ -1242,3 +1212,140 @@ def f():
12421212
def f():
12431213
household.join(log_return, how='outer')
12441214
self.assertRaises(NotImplementedError, f)
1215+
1216+
1217+
class TestMergeDtypes(tm.TestCase):
1218+
1219+
def setUp(self):
1220+
1221+
self.df = DataFrame(
1222+
{'A': ['foo', 'bar'],
1223+
'B': Series(['foo', 'bar']).astype('category'),
1224+
'C': [1, 2],
1225+
'D': [1.0, 2.0],
1226+
'E': Series([1, 2], dtype='uint64'),
1227+
'F': Series([1, 2], dtype='int32')})
1228+
1229+
def test_different(self):
1230+
1231+
# we expect differences by kind
1232+
# to be ok, while other differences should return object
1233+
1234+
left = self.df
1235+
for col in self.df.columns:
1236+
right = DataFrame({'A': self.df[col]})
1237+
result = pd.merge(left, right, on='A')
1238+
assert is_object_dtype(result.A.dtype)
1239+
1240+
def test_join_multi_dtypes(self):
1241+
1242+
# test with multi dtypes in the join index
1243+
def _test(dtype1, dtype2):
1244+
left = DataFrame({'k1': np.array([0, 1, 2] * 8, dtype=dtype1),
1245+
'k2': ['foo', 'bar'] * 12,
1246+
'v': np.array(np.arange(24), dtype=np.int64)})
1247+
1248+
index = MultiIndex.from_tuples([(2, 'bar'), (1, 'foo')])
1249+
right = DataFrame(
1250+
{'v2': np.array([5, 7], dtype=dtype2)}, index=index)
1251+
1252+
result = left.join(right, on=['k1', 'k2'])
1253+
1254+
expected = left.copy()
1255+
1256+
if dtype2.kind == 'i':
1257+
dtype2 = np.dtype('float64')
1258+
expected['v2'] = np.array(np.nan, dtype=dtype2)
1259+
expected.loc[(expected.k1 == 2) & (expected.k2 == 'bar'), 'v2'] = 5
1260+
expected.loc[(expected.k1 == 1) & (expected.k2 == 'foo'), 'v2'] = 7
1261+
1262+
tm.assert_frame_equal(result, expected)
1263+
1264+
result = left.join(right, on=['k1', 'k2'], sort=True)
1265+
expected.sort_values(['k1', 'k2'], kind='mergesort', inplace=True)
1266+
tm.assert_frame_equal(result, expected)
1267+
1268+
for d1 in [np.int64, np.int32, np.int16, np.int8, np.uint8]:
1269+
for d2 in [np.int64, np.float64, np.float32, np.float16]:
1270+
_test(np.dtype(d1), np.dtype(d2))
1271+
1272+
1273+
class TestMergeCategorical(tm.TestCase):
1274+
_multiprocess_can_split_ = True
1275+
1276+
def setUp(self):
1277+
np.random.seed(1234)
1278+
self.left = DataFrame(
1279+
{'X': Series(np.random.choice(
1280+
['foo', 'bar'],
1281+
size=(10,))).astype('category', categories=['foo', 'bar']),
1282+
'Y': np.random.choice(['one', 'two', 'three'], size=(10,))})
1283+
self.right = pd.DataFrame(
1284+
{'X': Series(['foo', 'bar']).astype('category',
1285+
categories=['foo', 'bar']),
1286+
'Z': [1, 2]})
1287+
1288+
def test_identical(self):
1289+
# merging on the same, should preserve dtypes
1290+
merged = pd.merge(self.left, self.left, on='X')
1291+
result = merged.dtypes.sort_index()
1292+
expected = Series([CategoricalDtype(),
1293+
np.dtype('O'),
1294+
np.dtype('O')],
1295+
index=['X', 'Y_x', 'Y_y'])
1296+
assert_series_equal(result, expected)
1297+
1298+
def test_basic(self):
1299+
# we have matching Categorical dtypes in X
1300+
# so should preserve the merged column
1301+
merged = pd.merge(self.left, self.right, on='X')
1302+
result = merged.dtypes.sort_index()
1303+
expected = Series([CategoricalDtype(),
1304+
np.dtype('O'),
1305+
np.dtype('int64')],
1306+
index=['X', 'Y', 'Z'])
1307+
assert_series_equal(result, expected)
1308+
1309+
def test_other_columns(self):
1310+
# non-merge columns should preserve if possible
1311+
left = self.left
1312+
right = self.right.assign(Z=self.right.Z.astype('category'))
1313+
1314+
merged = pd.merge(left, right, on='X')
1315+
result = merged.dtypes.sort_index()
1316+
expected = Series([CategoricalDtype(),
1317+
np.dtype('O'),
1318+
CategoricalDtype()],
1319+
index=['X', 'Y', 'Z'])
1320+
assert_series_equal(result, expected)
1321+
1322+
# categories are preserved
1323+
assert left.X.values.is_dtype_equal(merged.X.values)
1324+
assert right.Z.values.is_dtype_equal(merged.Z.values)
1325+
1326+
def test_dtype_on_merged_different(self):
1327+
# our merging columns, X now has 2 different dtypes
1328+
# so we must be object as a result
1329+
left = self.left
1330+
1331+
for change in [lambda x: x,
1332+
lambda x: x.astype('category',
1333+
categories=['bar', 'foo']),
1334+
lambda x: x.astype('category',
1335+
categories=['foo', 'bar', 'bah']),
1336+
lambda x: x.astype('category', ordered=True)]:
1337+
for how in ['inner', 'outer', 'left', 'right']:
1338+
1339+
X = change(self.right.X.astype('object'))
1340+
right = self.right.assign(X=X)
1341+
assert is_categorical_dtype(left.X.values)
1342+
assert not left.X.values.is_dtype_equal(right.X.values)
1343+
1344+
merged = pd.merge(left, right, on='X', how=how)
1345+
1346+
result = merged.dtypes.sort_index()
1347+
expected = Series([np.dtype('O'),
1348+
np.dtype('O'),
1349+
np.dtype('int64')],
1350+
index=['X', 'Y', 'Z'])
1351+
assert_series_equal(result, expected)

pandas/tests/tools/test_merge_asof.py

+1
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ def test_basic_categorical(self):
147147
trades.ticker = trades.ticker.astype('category')
148148
quotes = self.quotes.copy()
149149
quotes.ticker = quotes.ticker.astype('category')
150+
expected.ticker = expected.ticker.astype('category')
150151

151152
result = merge_asof(trades, quotes,
152153
on='time',

pandas/tests/types/test_common.py

+27-10
Original file line numberDiff line numberDiff line change
@@ -39,16 +39,33 @@ def test_period_dtype(self):
3939

4040

4141
def test_dtype_equal():
42-
assert is_dtype_equal(np.int64, np.int64)
43-
assert not is_dtype_equal(np.int64, np.float64)
4442

45-
p1 = PeriodDtype('D')
46-
p2 = PeriodDtype('D')
47-
assert is_dtype_equal(p1, p2)
48-
assert not is_dtype_equal(np.int64, p1)
43+
dtypes = dict(dt_tz=pandas_dtype('datetime64[ns, US/Eastern]'),
44+
dt=pandas_dtype('datetime64[ns]'),
45+
td=pandas_dtype('timedelta64[ns]'),
46+
p=PeriodDtype('D'),
47+
i=np.int64,
48+
f=np.float64,
49+
o=np.object)
4950

50-
p3 = PeriodDtype('2D')
51-
assert not is_dtype_equal(p1, p3)
51+
# match equal to self, but not equal to other
52+
for name, dtype in dtypes.items():
53+
assert is_dtype_equal(dtype, dtype)
5254

53-
assert not DatetimeTZDtype.is_dtype(np.int64)
54-
assert not PeriodDtype.is_dtype(np.int64)
55+
for name2, dtype2 in dtypes.items():
56+
if name != name2:
57+
assert not is_dtype_equal(dtype, dtype2)
58+
59+
# we are strict on kind equality
60+
for dtype in [np.int8, np.int16, np.int32]:
61+
assert not is_dtype_equal(dtypes['i'], dtype)
62+
63+
for dtype in [np.float32]:
64+
assert not is_dtype_equal(dtypes['f'], dtype)
65+
66+
# strict w.r.t. PeriodDtype
67+
assert not is_dtype_equal(dtypes['p'], PeriodDtype('2D'))
68+
69+
# strict w.r.t. datetime64
70+
assert not is_dtype_equal(dtypes['dt_tz'],
71+
pandas_dtype('datetime64[ns, CET]'))

0 commit comments

Comments
 (0)