Skip to content

Commit 7d550ef

Browse files
committed
Merge pull request #9929 from mortada/add_categories
Allow add_categories() to accept Series/np.array and make raising on dup...
2 parents 6908719 + 29c2001 commit 7d550ef

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

doc/source/whatsnew/v0.16.1.txt

+1
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ Enhancements
6161
- Allow Panel.shift with ``axis='items'`` (:issue:`9890`)
6262

6363
- Trying to write an excel file now raises ``NotImplementedError`` if the ``DataFrame`` has a ``MultiIndex`` instead of writing a broken Excel file. (:issue:`9794`)
64+
- Allow ``Categorical.add_categories`` to accept `Series` or `np.array`. (:issue:`9927`)
6465

6566
- Add/delete ``str/dt/cat`` accessors dynamically from ``__dir__``. (:issue:`9910`)
6667

pandas/core/categorical.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -708,7 +708,7 @@ def add_categories(self, new_categories, inplace=False):
708708
if len(already_included) != 0:
709709
msg = "new categories must not include old categories: %s" % str(already_included)
710710
raise ValueError(msg)
711-
new_categories = list(self._categories) + (new_categories)
711+
new_categories = list(self._categories) + list(new_categories)
712712
new_categories = self._validate_categories(new_categories)
713713
cat = self if inplace else self.copy()
714714
cat._categories = new_categories

pandas/tests/test_categorical.py

+13
Original file line numberDiff line numberDiff line change
@@ -757,6 +757,19 @@ def f():
757757
cat.add_categories(["d"])
758758
self.assertRaises(ValueError, f)
759759

760+
# GH 9927
761+
cat = Categorical(list("abc"), ordered=True)
762+
expected = Categorical(list("abc"), categories=list("abcde"), ordered=True)
763+
# test with Series, np.array, index, list
764+
res = cat.add_categories(Series(["d", "e"]))
765+
self.assert_categorical_equal(res, expected)
766+
res = cat.add_categories(np.array(["d", "e"]))
767+
self.assert_categorical_equal(res, expected)
768+
res = cat.add_categories(Index(["d", "e"]))
769+
self.assert_categorical_equal(res, expected)
770+
res = cat.add_categories(["d", "e"])
771+
self.assert_categorical_equal(res, expected)
772+
760773
def test_remove_categories(self):
761774
cat = Categorical(["a","b","c","a"], ordered=True)
762775
old = cat.copy()

0 commit comments

Comments
 (0)