Skip to content

Commit 252526c

Browse files
BUG/API: Index.append with mixed object/Categorical indices (#14545)
* BUG/API: Index.append with mixed object/Categorical indices * Only coerce to object if the calling index is not categorical * Add test for the df.info() case (GH14298)
1 parent 7f0c4e0 commit 252526c

File tree

3 files changed

+17
-4
lines changed

3 files changed

+17
-4
lines changed

pandas/indexes/base.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1464,13 +1464,13 @@ def append(self, other):
14641464
names = set([obj.name for obj in to_concat])
14651465
name = None if len(names) > 1 else self.name
14661466

1467-
typs = _concat.get_dtype_kinds(to_concat)
1468-
1469-
if 'category' in typs:
1470-
# if any of the to_concat is category
1467+
if self.is_categorical():
1468+
# if calling index is category, don't check dtype of others
14711469
from pandas.indexes.category import CategoricalIndex
14721470
return CategoricalIndex._append_same_dtype(self, to_concat, name)
14731471

1472+
typs = _concat.get_dtype_kinds(to_concat)
1473+
14741474
if len(typs) == 1:
14751475
return self._append_same_dtype(to_concat, name=name)
14761476
return _concat._concat_index_asobject(to_concat, name=name)

pandas/tests/frame/test_repr_info.py

+8
Original file line numberDiff line numberDiff line change
@@ -405,3 +405,11 @@ def memory_usage(f):
405405

406406
# high upper bound
407407
self.assertTrue(memory_usage(unstacked) - memory_usage(df) < 2000)
408+
409+
def test_info_categorical(self):
410+
# GH14298
411+
idx = pd.CategoricalIndex(['a', 'b'])
412+
df = pd.DataFrame(np.zeros((2, 2)), index=idx, columns=idx)
413+
414+
buf = StringIO()
415+
df.info(buf=buf)

pandas/tests/indexes/test_category.py

+5
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,11 @@ def test_append(self):
278278
# invalid objects
279279
self.assertRaises(TypeError, lambda: ci.append(Index(['a', 'd'])))
280280

281+
# GH14298 - if base object is not categorical -> coerce to object
282+
result = Index(['c', 'a']).append(ci)
283+
expected = Index(list('caaabbca'))
284+
tm.assert_index_equal(result, expected, exact=True)
285+
281286
def test_insert(self):
282287

283288
ci = self.create_index()

0 commit comments

Comments
 (0)