From 29c2001905145cd1f97c33273963ea4f8db2a81e Mon Sep 17 00:00:00 2001 From: Mortada Mehyar Date: Mon, 20 Apr 2015 14:45:18 -0700 Subject: [PATCH] Allow add_categories() to accept Series/np.array --- doc/source/whatsnew/v0.16.1.txt | 1 + pandas/core/categorical.py | 2 +- pandas/tests/test_categorical.py | 13 +++++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt index 659aa6786b366..29ea267ed583b 100755 --- a/doc/source/whatsnew/v0.16.1.txt +++ b/doc/source/whatsnew/v0.16.1.txt @@ -55,6 +55,7 @@ Enhancements - Allow Panel.shift with ``axis='items'`` (:issue:`9890`) - Trying to write an excel file now raises ``NotImplementedError`` if the ``DataFrame`` has a ``MultiIndex`` instead of writing a broken Excel file. (:issue:`9794`) +- Allow ``Categorical.add_categories`` to accept `Series` or `np.array`. (:issue:`9927`) .. _whatsnew_0161.api: diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py index 0d66a89b0a585..cd98e7bb91045 100644 --- a/pandas/core/categorical.py +++ b/pandas/core/categorical.py @@ -687,7 +687,7 @@ def add_categories(self, new_categories, inplace=False): if len(already_included) != 0: msg = "new categories must not include old categories: %s" % str(already_included) raise ValueError(msg) - new_categories = list(self._categories) + (new_categories) + new_categories = list(self._categories) + list(new_categories) new_categories = self._validate_categories(new_categories) cat = self if inplace else self.copy() cat._categories = new_categories diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py index af48774492b11..0095e232f2530 100644 --- a/pandas/tests/test_categorical.py +++ b/pandas/tests/test_categorical.py @@ -727,6 +727,19 @@ def f(): cat.add_categories(["d"]) self.assertRaises(ValueError, f) + # GH 9927 + cat = Categorical(list("abc"), ordered=True) + expected = Categorical(list("abc"), categories=list("abcde"), ordered=True) + # test with Series, np.array, index, list + res = cat.add_categories(Series(["d", "e"])) + self.assert_categorical_equal(res, expected) + res = cat.add_categories(np.array(["d", "e"])) + self.assert_categorical_equal(res, expected) + res = cat.add_categories(Index(["d", "e"])) + self.assert_categorical_equal(res, expected) + res = cat.add_categories(["d", "e"]) + self.assert_categorical_equal(res, expected) + def test_remove_categories(self): cat = Categorical(["a","b","c","a"], ordered=True) old = cat.copy()