Skip to content

Commit cfeafbb

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

File tree

8 files changed

+277
-69
lines changed

8 files changed

+277
-69
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

+10
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,7 @@ Other API Changes
431431
- ``DataFrame.asof()`` will return a null filled ``Series`` instead the scalar ``NaN`` if a match is not found (:issue:`15118`)
432432
- 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`).
433433
- Reorganization of timeseries development tests (:issue:`14854`)
434+
- ``.merge()`` and ``.join()`` on ``category`` dtype columns will now preserve the category dtype when possible (:issue:`10409`)
434435

435436
.. _whatsnew_0200.deprecations:
436437

@@ -472,8 +473,17 @@ Performance Improvements
472473
- Improved performance of timeseries plotting with an irregular DatetimeIndex
473474
(or with ``compat_x=True``) (:issue:`15073`).
474475
- Improved performance of ``groupby().cummin()`` and ``groupby().cummax()`` (:issue:`15048`, :issue:`15109`)
476+
<<<<<<< e351ed0fd211a204f960b9116bc13f75ed1f97c4
475477
- Improved performance and reduced memory when indexing with a ``MultiIndex`` (:issue:`15245`)
478+
<<<<<<< 5a8883b965610234366150897fe8963abffd6a7c
476479
- When reading buffer object in ``read_sas()`` method without specified format, filepath string is inferred rather than buffer object. (:issue:`14947`)
480+
=======
481+
=======
482+
- Improved performance of merge/join on ``category`` columns (:issue:`10409`)
483+
484+
>>>>>>> BUG/API: .merge() and .join() on category dtype columns will now preserve the category dtype when possible
485+
- When reading buffer object in ``read_sas()`` method without specified format, filepath string is inferred rather than buffer object.
486+
>>>>>>> BUG/API: .merge() and .join() on category dtype columns will now preserve the category dtype when possible
477487

478488

479489

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

@@ -1016,38 +1018,6 @@ def test_left_join_index_multi_match(self):
10161018
expected.index = np.arange(len(expected))
10171019
tm.assert_frame_equal(result, expected)
10181020

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