Skip to content

Allow add_categories() to accept Series/np.array and make raising on dup... #9929

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 21, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.16.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions pandas/tests/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down